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

hkB*_*sai 2 c++ winapi multithreading 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
Run Code Online (Sandbox Code Playgroud)

错误给出:

[Line 66] Error C2248: 'std::thread::thread' : cannot access private member declared in class 'std::thread'

此错误消息对我没有帮助,我不是要尝试访问std::thread该类的任何私有成员.

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

Cas*_*sey 7

在这一行:

MessageLoopThread = std::thread(&GenericWindow::MessageLoop, *this);
Run Code Online (Sandbox Code Playgroud)

您将*this值传递给std::thread构造函数,构造函数将尝试将副本传递给新生成的线程.*this当然是不可复制的,因为它有一个std::thread成员.如果要传递引用,则需要将其放在std::reference_wrapper:

MessageLoopThread = std::thread(&GenericWindow::MessageLoop,
                                std::ref(*this));
Run Code Online (Sandbox Code Playgroud)

  • [我决定从现在起每天都要回答一个问题](http://stackoverflow.com/a/18152978/923854). (2认同)