Is it possible to define an std::thread and initialize it later?
c++, copy-constructor, stdthread
Solution
Your problem is something else - you're passing an instance of `MyClass` into the thread instead of the pointer to `MyClass` which the member functions expect. Simply change `DoDiskJobThread()` like this (do not dereference `this`):
void MyClass::DoDiskJobThread()
{
std::wstring Source = GetSource();
std::wstring Target = GetTarget();
int m_OperationType = GetOperationType();
if (m_OperationType == OPERATION_COPY)
{
DiskJobThread = std::thread(&MyClass::CopyThread, this, Source, Target);
}
else if (m_OperationType == OPERATION_MOVE)
{
DiskJobThread = std::thread(&MyClass::MoveThread, this, Source, Target);
}
}
You were getting the error because `*this` resulted in trying to copy `MyClass` into the thread function, and the copy ctor of your class is deleted (because that of `std::thread` is deleted). However, the member functions `CopyThread` and `MoveThread` require a pointer as the first (hidden) argument anyway.
Live demonstration
Problem
My aim is to keep an `std::thread` object as data member, and initialize it when needed. I'm not able to do this (as in my code below) because the copy constructor of the `std::thread` class is deleted. Is there any other way to do it? ``` class MyClass { public: MyClass():DiskJobThread(){}; ~MyClass(); void DoDiskJobThread(); private: int CopyThread(const std::wstring & Source, const std::wstring & Target); int MoveThread(const std::wstring & Source, const std::wstring & Target); std::thread DiskJobThread; }; MyClass::~MyClass() { DiskJobThread.join(); } void MyClass::DoDiskJobThread() { std::wstring Source = GetSource(); std::wstring Target = GetTarget(); int m_OperationType = GetOperationType(); if (m_OperationType == OPERATION_COPY) { DiskJobThread = std::thread(&MyClass::CopyThread, *this, Source, Target); } else if (m_OperationType == OPERATION_MOVE) { DiskJobThread = std::thread(&MyClass::MoveThread, *this, Source, Target); } } ```