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

标签 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 类的任何私有(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/

相关文章:

c++ - 将比特流捕获到字符串中

c++ - 这是一个糟糕的 C++ 对象构造吗?

c++ - OpenCV 修改图像像素

c# - 如何在线程上调用泛型方法?

java - 了解多处理器同步

windows - 如何永久终止 Windows 资源管理器( "explorer.exe"进程)?

c++ - UNICODE_STRING 到 wchar_t* null 终止

c++ - 如何控制返回对象的拷贝到新对象中?

Java信号量同步打印到屏幕

c - Win32 - 在创建窗口之前拦截窗口的更好方法