Storing an std::thread object as a class member

允我心安 提交于 2020-01-02 09:42:14

问题


I'm trying to keep an std::thread object inside a class.

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

Error given:

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

This error message doesn't help me, I'm not trying to access any private member of the std::thread class.

What is wrong in my code? How do I fix it?


回答1:


On this line:

MessageLoopThread = std::thread(&GenericWindow::MessageLoop, *this);

You are passing *this by value to the std::thread constructor, which will try to make a copy to pass to the newly spawned thread. *this is of course noncopyable, since it has a std::thread member. If you want to pass a reference, you need to put it in a std::reference_wrapper:

MessageLoopThread = std::thread(&GenericWindow::MessageLoop,
                                std::ref(*this));


来源:https://stackoverflow.com/questions/18163284/storing-an-stdthread-object-as-a-class-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!