我正在尝试在类中保留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
类的任何私有成员。
我的代码有什么问题?我该如何解决?
答案 0 :(得分:7)
在这一行:
MessageLoopThread = std::thread(&GenericWindow::MessageLoop, *this);
您将*this
按值传递给std::thread
构造函数,该构造函数将尝试将副本传递给新生成的线程。 *this
当然是不可复制的,因为它有一个std::thread
成员。如果您想传递参考,则需要将其放入std::reference_wrapper
:
MessageLoopThread = std::thread(&GenericWindow::MessageLoop,
std::ref(*this));