Say you have a class which is a global (e.g. available for the runtime of the app)
class MyClass {
protected:
std::string m_Value;
public:
MyClass () : m_Value("hello") {}
std::string value() { return m_Value; }
};
MyClass v1;
Using the first form gives me odd behavior when I do
printf("value: %s\n", v1.value().c_str());
It looks as though the string disappears from memory before printf can use it. Sometimes it prints value: hello other times it crashes or prints nothing.
If I first copy the string like so
std::string copiedString = v1.value();
printf("value: %s\n", copiedString.c_str());
things do work.
Surely there must be a way to avoid doing this with a temporary string.
Edit: So the consensus is to go with a const std::string & return value.
I know everyone says that the original code should be fine but I can tell you that I've seen MSVC 2005 on Windows CE having trouble with it, but only on the CE box. Not the Win32 cross compile.