我试图在一个类中保留一个 std::thread
对象。
class GenericWindow
{
public:
void Create()
{
// ...
MessageLoopThread = std::thread(&GenericWindow::MessageLoop, *this);
}
private:
std::thread MessageLoopThread;
void GenericWindow::Destroy() // Called from the destructor
{
SendMessageW(m_hWnd, WM_DESTROY, NULL, NULL);
UnregisterClassW(m_ClassName.c_str(), m_WindowClass.hInstance);
MessageLoopThread.join();
}
void GenericWindow::MessageLoop()
{
MSG Msg;
while (GetMessageW(&Msg, NULL, 0, 0))
{
if (!IsDialogMessageW(m_hWnd, &Msg))
{
TranslateMessage(&Msg);
DispatchMessageW(&Msg);
}
}
}
}; // LINE 66
给出的错误:
[Line 66] Error C2248: 'std::thread::thread' : cannot access private member declared in class 'std::thread'
此错误消息对我没有帮助,我没有尝试访问 std::thread
类的任何私有(private)成员。
我的代码有什么问题?我该如何解决?
最佳答案
在这一行:
MessageLoopThread = std::thread(&GenericWindow::MessageLoop, *this);
您正在将 *this
按值传递给 std::thread
构造函数,它将尝试制作一个拷贝以传递给新生成的线程。 *this
当然是不可复制的,因为它有一个 std::thread
成员。如果你想传递一个引用,你需要把它放在一个std::reference_wrapper
中:
MessageLoopThread = std::thread(&GenericWindow::MessageLoop,
std::ref(*this));
关于c++ - 将 std::thread 对象存储为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18163284/