C++ MessageBox线程问题

C++ MessageBox线程问题,c++,multithreading,variables,visual-c++,messagebox,C++,Multithreading,Variables,Visual C++,Messagebox,我在使用以下代码的线程中启动了Messagebox的一个奇怪行为: 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);

我在使用以下代码的线程中启动了Messagebox的一个奇怪行为:

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”。

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

你能举个例子吗?我不明白你的确切意思。如果我将msg声明为static(我认为这是最简单的),我有一个分段错误,所以我把它改了回去,因为你写的不是一个好主意。你能给我一个例子,你对其他两件事的意思是什么吗?如果你使用静态变量,你不应该得到访问冲突。无论如何,关于第三个选项,你在某个类中有这个代码,对吗?我的意思是你用“c++”标记了你的问题。然后dd
std::string msg
作为该类的成员变量。