0

我使用以下代码在线程中启动了消息框的奇怪行为:

DWORD WINAPI CreateMessageBox(LPVOID lpParam) {
    MessageBoxA(NULL, (char*)lpParam, "", MB_OK);
    return 0;
}
std::string msg = "Hello World";
CreateThread(NULL, 0, &CreateMessageBox, msg.c_str(), 0, NULL);

虽然此代码正常工作:

DWORD WINAPI CreateMessageBox(LPVOID lpParam) {
    MessageBoxA(NULL, (char*)lpParam, "", MB_OK);
    return 0;
}
CreateThread(NULL, 0, &CreateMessageBox, "Hello World", 0, NULL);

我不明白为什么当它不是变量时它会起作用,如果我将它更改为变量,则会显示一个空消息框,但我期望一个“Hello World!.

4

1 回答 1

0

msg是一个局部变量(在堆栈上分配),一旦包含该代码的函数/方法返回,它将被销毁。因此,线程在使用lparam.

一些解决方案可能是:

1.) declare 'msg' as static - probably not a good idea
2.) allocate 'msg' on heap, but then you will have to destroy it somewhere
3.) make 'msg' a member variable
于 2013-10-09T20:55:20.370 回答