c++ - 如何测试 std::thread 是否被移出?

标签 c++ multithreading c++11 move-semantics

我有一个带有 std::thread 成员的可 move 不可复制类。

当类析构函数运行时,我需要做一些清理工作并加入线程。 如果类从中移出,我需要析构函数跳过清理和线程连接。 我可以通过存储从中移出的 bool 值来完成此操作,但这似乎有点浪费。

如果 std::thread 成员被移出,那么我知道这个类实例被移出。是否可以检查 std::thread 成员是否被 move ?

class Widget
{
    Widget()
    {
        // initialize
    }

    Widget( Widget&& rhs )
    {
        t = std::move(rhs.t);
    }

    ~Widget()
    {
        if ( t_is_not_moved_from() )
        {
            // do cleanup
            t.join();
        }
    }

    inline friend void swap( Widget& lhs, Widget& rhs )
    {
        lhs.t.swap( rhs.t );
    }

private:
    std::thread t;

    // noncopyable
    Widget( const Widget& );
    const Widget& operator=( const Widget& );
};

最佳答案

与大多数标准库对象不同,std::thread 的 move 构造函数确实明确规定了移出的线程 的状态。它等同于一个空线程:thread.joinable 将为 false

关于c++ - 如何测试 std::thread 是否被移出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16128279/

相关文章:

c++ - Visual Studio 2017 中是否有自动保存功能来处理其错误和崩溃?

C++ chrono - 将持续时间作为 float 或 long long

multithreading - 使用2个线程在串口上同时读写

c++ - 局部静态指针变量不是线程安全的?

c++ - 为可变参数模板添加的新语法实体的名称是什么?

c++ - 如何在 DDD(或 gdb)中使用 unique_ptr 调试 C++11 代码?

linux - 使用 boost 和 C++11 构建进程崩溃

c++ - 从命令行 (C++) 调用时转换无效

ios - HTTP 数据任务 (NSURLSessionDataTask) 的 NSURLSession 是否在后台线程中运行,或者我们必须提供队列?

c++ - C++结构语法 “a : b”是什么意思