是否可以定义std :: thread并稍后对其进行初始化? [英] Is it possible to define an std::thread and initialize it later?
问题描述
我的目标是保留 std :: thread
对象作为数据成员,并在需要时对其进行初始化。
我无法这样做(如下面的代码所示)是因为 std :: thread
类的副本构造函数被删除了。还有其他方法吗?
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);
}
}
推荐答案
您的问题是另外一回事-您正在将 MyClass
的实例传递到线程中,而不是指向 MyClass
的指针。成员函数期望。只需像这样更改 DoDiskJobThread()
(不要取消引用 this
):
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);
}
}
由于 *此
导致尝试将 MyClass
复制到线程函数中,并且类的副本ctor被删除(因为 std :: thread
被删除)。但是,成员函数 CopyThread
和 MoveThread
仍然需要一个指针作为第一个(隐藏的)参数。
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
这篇关于是否可以定义std :: thread并稍后对其进行初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!