M D M D -4 years ago 181
C++ Question

Faulty conversion, std::string -> LPCSTR

I have a function Analyze_, that returns a std::string with some info in it, I
want it in LPCSTR form though.
When I use c_str() like this, it works and l stores my information:

std::string s = myClassInstance.Analyze_();
LPCSTR l = s.c_str();

But when I write it shorter, like the following, I get a series of 'Ỳ's:

LPCSTR l = myClassInstance.Analyze_().c_str();

Is it calling c_str() before Analyze_()? I guess that should be impossible
because it's a function, not a string.

I tried other solutions, such as directly converting it from the stringstream that generates the string and just return that, like so:

std::stringstream ss;
ss << "Bla blub...\n";
return ss.str().c_str();

But I have the same problem there.
Why is this happening?

Answer Source

c_str() returns a const char* to the internal buffer of the std::string. Chaining method calls like you're doing here LPCSTR l = myClassInstance.Analyze_().c_str(); creates a temporary std::string (the return of Analyze()) and then returns the pointer to the internal buffer of that string. Then, the string is destroyed and you're left with a dangling pointer, Undefined Behaviour when trying to derefence. Just save the std::string if you want to use a pointer to it's buffer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download