I have a member function defined as below:
std::string returnStringMethod()
{
return /* some string */;
}
The caller looks like this:
const char * ptr = returnStringMethod().c_str();
This is returning some truncated string which I did not expect. However, the following works fine:
std::string str = returnStringMethod();
const char * ptr = str.c_str();
What is happening here?
const char * ptr = returnStringMethod().c_str();
In above line a temp string is returned by the function which soon goes out of scope. (and destructor is called and memory is freed)
In later version you make a local copy of string and thus the behaviour is defined.
You can also use the following
const std::string &str = returnStringMethod();
const char * ptr = str.c_str();
Using const reference would lengthen the life of temporary variable until the reference is in scope and there would be no (explicit) unwanted copies.