I was playing with some strings when I stumbled upon a weird behavior while converting a std::string to a LPCSTR.
I have written a small test application to demonstrate :
#include <string>
#include <Windows.h>
#include <iostream>
using namespace std;
int main ()
{
string stringTest = (string("some text") + " in addition with this other text").c_str();
LPCSTR lpstrTest= stringTest.c_str();
cout << lpcstrTest << '\n';
cout << (string("some text") + " in addition with this other text").c_str() << '\n';
LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();
cout << otherLPSTR;
}
And here is the output :
some text in addition with this other text
some text in addition with this other text
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ...[more unreadable stuff]...
I am simply wondering what is causing this strange behavior.
Thank you
The part
creates a so-called “temporary” object, which has no name and gets destructed when the statement that contains it finishes. You get the c_str() from that, which points to some internal storage of that temporary object. You assign that c_str() to the otherLPCSTR variable. After that, “the statment that contains the temporary string” has finished, so the temporary string gets destructed, and the otherLPCSTR points “nowhere”.