如何测试一个std::线程是否从

How do I test if a std::thread is moved from?

本文关键字:std 是否 一个 线程 何测试 测试      更新时间:2023-10-16

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

当类析构函数运行时,我需要做一些清理工作并加入线程。如果类被移动,我需要析构函数跳过清理和线程连接。我可以通过存储一个移动后的bool值来实现这一点,但这似乎有点浪费。

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

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移出的状态。这相当于一个空线程:thread.joinable将是false

相关文章: