是否可以定义一个std :: thread并在以后初始化它?

hkB*_*sai 18 c++ copy-constructor stdthread

我的目标是将std::thread对象保留为数据成员,并在需要时对其进行初始化.
我无法执行此操作(如下面的代码中所示),因为类的复制构造函数std::thread已被删除.还有其他办法吗?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Moh*_*oun 11

把它包在指针里怎么样?

std::unique_ptr<std::thread> thread_ptr;

// Look into std::make_unique if possible
thread_ptr = std::unique_ptr<std::thread>(new std::thread(...));
Run Code Online (Sandbox Code Playgroud)

编辑:是的,其他人已经提到了它,我觉得不需要在这里添加它,但为了避免更多的downvote打桩,我会说:你正在传递*this而不是this因此复制你的班级实例.(问题出现是因为它是不可复制的.通过this,你应该很好.)


Pet*_*ker 9

在创建线程对象后,无法对其进行初始化 ; 根据定义,在创建对象时进行初始化.但您可以使用swap将线程对象移动到另一个:

std::thread thr1; // no thread of execution
std::thread thr2(my_function_object); // creates thread of execution
thr1.swap(thr2);  // thr1 is now running the thread created as thr2
                  // and thr2 has no thread of execution
Run Code Online (Sandbox Code Playgroud)


Rei*_*ica 6

您的问题还有其他问题-您正在将的实例传递MyClass给线程,而不是MyClass成员函数期望的指针。DoDiskJobThread()像这样简单地更改(不要取消引用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

您收到此错误是因为*this试图复制MyClass到线程函数中,并且类的复制ctor被删除(因为的ctor std::thread被删除)。但是,该成员起作用CopyThread并且MoveThread无论如何都需要一个指针作为第一个(隐藏的)参数。

现场表演