繁体   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