Convert wstringstream to LPCWSTR

1.3k views Asked by At

I am a beginner at Winapi and I am trying to convert wstringstream to LPCWSTR like this (inside WM_PAINT):

wstringstream ws; 
ws << "my text" << endl; 
LPCWSTR myWindowOutput = ws.str().c_str();
hdc = BeginPaint(hWnd, &ps); 
TextOut(hdc, 150, 305, myWindowOutput, 10);

It only produces rubbish though, can somebody help? Thank you.

1

There are 1 answers

0
IInspectable On BEST ANSWER

LPCWSTR myWindowOutput = ws.str().c_str() produces a temporary (the return value of the str() call), that's gone as soon as the full statement ends. Since you need the temporary, you need to move it down to the call, that eventually consumes it:

TextOutW(hdc, 150, 305, ws.str().c_str(), static_cast<int>(ws.str().length()));

Again, the temporary lives until the full statement ends. This time around, this is long enough for the API call to use it.

As an alternative, you could bind the return value of str() to a const reference1), and use that instead. This may be more appropriate, since you need to use the return value twice (to get a pointer to the buffer, and to determine its size):

wstringstream ws;
ws << "my text" << endl;
hdc = BeginPaint(hWnd, &ps);
const wstring& s = ws.str();
TextOutW(hdc, 150, 305, s.c_str(), static_cast<int>(s.length()));


1) Why this works is explained under GotW #88: A Candidate For the “Most Important const”.