Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly return std::string (or how to properly use that returned value)

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.

like image 584
Ron Avatar asked Jan 06 '11 22:01

Ron


2 Answers

Your code should work fine. Something else is wrong, that we can't detect from this testcase. Perhaps run your executable through valgrind to search for memory errors.

like image 120
Lightness Races in Orbit Avatar answered Sep 22 '22 05:09

Lightness Races in Orbit


Well, there's nothing wrong with the code (as I interpret it). It is not optimal and surely not The Right Way (R), you should modify your code like villentehaspam suggests. As it is now, your code makes a copy of the string m_value because you return by value, which is not as good as only returning a const reference.

If you provide a complete code sample that shows the problem, I could help you better.

like image 29
rubenvb Avatar answered Sep 21 '22 05:09

rubenvb