Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert wstringstream to LPCWSTR

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.

like image 858
Johan Avatar asked Mar 27 '26 00:03

Johan


1 Answers

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”.
like image 68
IInspectable Avatar answered Mar 31 '26 03:03

IInspectable



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!