i have some sample code that behaves different in gcc(6.3)
and in MSVC (11)
. I know that passing raw "hello"
is not going to last when i call std::cout
. In Microsoft Visual Studio 11 i get the expected output but in gcc
the string remains in memory. The problem is that the code in gcc
may compile, may behave as expected but is wrong, and i do not know why did not erase the "hello" string from memory. What i am missing? (Ignore the memory leaks is just dummy code)
Edit
The question is more oriented about the difference of compiling with gcc
or MSVC
. I have already pointed that the code will yield into undefined behaviour. The point is that something like this has been running ok under linux during years and has crashed at first run under a Windows port. Maybe that was only luck but i was asking more about gcc
compiler doing nasty things in the background.
MSVC output
w_holder:
Gcc output
w_holder:hello
Code
#include <iostream>
#include <vector>
#include <string>
class StringWrapper
{
public:
StringWrapper(const std::string& sInput) : _string(sInput) { }
const std::string& _string;
};
class WrapperHolder
{
public:
WrapperHolder(const std::string& sInput) { _swrapper = new StringWrapper(sInput); }
StringWrapper* _swrapper;
};
int main()
{
WrapperHolder* w_holder = 0;
w_holder = new WrapperHolder("hello");
std::cout << "w_holder: " << w_holder->_swrapper->_string << std::endl;
return 0;
}