gpt4 book ai didi

c++ - 如果 const char* 从函数返回,则 LPCWSTR 损坏

转载 作者:行者123 更新时间:2023-11-27 22:34:02 25 4
gpt4 key购买 nike

我遇到了一个非常奇怪的问题。

我希望在 Windows 上使用 MessageBox(扩展为 MessageBoxW)输出一个简单的字符串。

以下是我使用的方法:

void MainWindow::ShowMessageBox( const std::wstring& title,const std::wstring& message ) const
{
MessageBox( hWnd,message.c_str(),title.c_str(),MB_OK );
}

std::wstring ConversionHelpers::s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;

len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);

wchar_t* buf = new wchar_t[len];

MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);

delete[] buf;
return r;
}

void DebugHelpers::MsgBox(MainWindow& window, const char* title, const char* message)
{
std::string t(title);
std::string m(message);

window.ShowMessageBox(ConversionHelpers::s2ws(t), ConversionHelpers::s2ws(m));
}

这个有效:

MsgBox(wnd, "Test", std::string("Hello").c_str());

这行不通:

const char* get_hello()
{
return std::string("Hello").c_str();
}

MsgBox(wnd, "Test", get_hello());

“不起作用”是指我收到了大量奇怪的字符。

我知道此示例中不需要转换,但在我的实现中,它是必需的。不过,这并没有回答关于奇怪的问题。

我对两者都做完全相同的事情,但其中一个使用方法返回值而不是直接访问它。

最佳答案

get_hello() 创建的 std::string 在退出时超出范围时被释放,留下返回的 char*在您甚至可以使用它之前指向无效内存。

最好让 get_hello() 返回 std::string,然后调用者可以调用 c_str()在返回的 std::string 上添加所需的:

std::string get_hello()
{
return std::string("Hello");
}

MsgBox(wnd, "Test", get_hello().c_str());

关于c++ - 如果 const char* 从函数返回,则 LPCWSTR 损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57128699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com