Reputation: 10911
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?
Upvotes: 2
Views: 3094
Reputation: 42544
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));
Upvotes: 7