簡體   English   中英

將 wstringstream 轉換為 LPCWSTR

[英]Convert wstringstream to LPCWSTR

我是 Winapi 的初學者,我正在嘗試像這樣(在 WM_PAINT 中)將 wstringstream 轉換為 LPCWSTR:

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

它只會產生垃圾,有人可以幫忙嗎? 謝謝你。

LPCWSTR myWindowOutput = ws.str().c_str()產生一個臨時的( str()調用的返回值),一旦完整的語句結束,它就會消失。 由於您需要臨時文件,您需要將其移至調用,最終會消耗它:

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

再次,臨時生命直到完整的語句結束。 這一次,這段時間足以讓 API 調用使用它。

作為替代方案,您可以將str()的返回值綁定到一個常量引用1) ,然后使用它。 這可能更合適,因為您需要兩次使用返回值(以獲取指向緩​​沖區的指針,並確定其大小):

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) GotW #88: A Candidate For the“最重要的常量”下解釋了為什么這有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM