C++ MessageBoxW函数的wostringstream到LPWSTR
在将wostringstream转换为LPCWSTR方面,我似乎遗漏了一些东西C++ MessageBoxW函数的wostringstream到LPWSTR,c++,C++,在将wostringstream转换为LPCWSTR方面,我似乎遗漏了一些东西 void counter_error(const wstring& input) { wostringstream tempss; tempss << L"Cannot find counter " << input; LPCWSTR temp = tempss.str().c_str(); MessageBoxW(0, temp, L"ERROR",
void counter_error(const wstring& input) {
wostringstream tempss;
tempss << L"Cannot find counter " << input;
LPCWSTR temp = tempss.str().c_str();
MessageBoxW(0, temp, L"ERROR", 0);
}
void计数器错误(常量wstring和输入){
Wostringstreamtemps;
tempss这条线看起来有问题:
LPCWSTR temp = tempss.str().c_str();
tempss.str()
试一试
它仍然会创建一个临时变量,但在从MessageBoxW
返回之前不会销毁它。这里不需要字符串流。temp
是一个悬空指针。或者只是MessageBoxW(0,(wstring(L“找不到计数器”)+输入。c_str(),…)
@JoachimPileborg是的,当然。我更新了答案。(我没有关注最短的解决方案,而是关注给定解决方案中的错误。)只是为了确保我理解这里的对象生命周期,LPCWSTR const&temp=tempss.str().c_str();将不起作用,因为尽管它延长了wchar_t*临时数组的生存期,但它不会延长tempss.str()返回的字符串(c_str()中的wchar_t*指向的底层数组)的生存期
void counter_error(const wstring& input) {
wostringstream tempss;
tempss << L"Cannot find counter " << input;
wstring temp_str = tempss.str();
LPCWSTR temp = temp_str.c_str();
MessageBoxW(0, temp, L"ERROR", 0);
}
MessageBoxW(0, (wstring(L"Cannot find counter " + input).c_str(), ...)