将std :: thread对象存储为类成员

时间:2013-08-10 15:17:50

标签: c++ multithreading winapi c++11 stdthread

我正在尝试在类中保留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类的任何私有成员。

我的代码有什么问题?我该如何解决?

1 个答案:

答案 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));