将std :: thread对象存储为类成员 [英] Storing an std::thread object as a class member
问题描述
我想在类中保留 std :: thread
对象。
class GenericWindow
{
public:
void Create()
{
// ...
MessageLoopThread = std :: thread(& GenericWindow :: MessageLoop,* this);
}
private:
std :: thread MessageLoopThread;
void GenericWindow :: Destroy()//从析构函数调用
{
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]错误C2248:'std :: thread :: thread':无法访问在'std :: thread'类中声明的私有成员
这个错误信息不帮助我,我不是试图访问 std :: thread
类的任何私人成员。
我的代码有什么问题?
$ p<$ p
MessageLoopThread = std :: thread(& GenericWindow :: MessageLoop,* this);
您将 * this
std :: thread
构造函数,它将尝试使副本传递到新生成的线程。 * this
当然是不可复制的,因为它有一个 std :: thread
成员。如果您要传递参考,则需要将其放在 std :: reference_wrapper
:
MessageLoopThread = std :: thread(& GenericWindow :: MessageLoop,
std :: ref(* this));
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?
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));
这篇关于将std :: thread对象存储为类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!