我有一个带有 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/