c++ - Weird behavior while converting a std::string to a LPCSTR -
i playing strings when stumbled upon weird behavior while converting std::string
lpcstr
.
i have written small test application demonstrate :
#include <string> #include <windows.h> #include <iostream> using namespace std; int main () { string stringtest = (string("some text") + " in addition other text").c_str(); lpcstr lpstrtest= stringtest.c_str(); cout << lpcstrtest << '\n'; cout << (string("some text") + " in addition other text").c_str() << '\n'; lpcstr otherlpcstr= (string("some text") + " in addition other text").c_str(); cout << otherlpstr; }
and here output :
some text in addition other text text in addition other text îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ...[more unreadable stuff]...
i wondering causing strange behavior.
thank you
lpcstr otherlpcstr= (string("some text") + " in addition other text").c_str(); cout << otherlpstr;
the part
(string("some text") + " in addition other text")
creates so-called "temporary" object, has no name , gets destructed when statement contains finishes. c_str() that, points internal storage of temporary object. assign c_str() otherlpcstr variable. after that, "the statment contains temporary string" has finished, temporary string gets destructed, , otherlpcstr points "nowhere".
Comments
Post a Comment