如何测试一个std::线程是否从
How do I test if a std::thread is moved from?
我有一个带有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
。
相关文章:
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 关于std::move的使用,是否有编译警告
- 通过网络、跨平台传递std::变体是否安全
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- std::vector::迭代器是否可以合法地作为指针
- MESI协议和std::atomic-它是否确保所有写入立即对其他线程可见?
- 是否将std::packaged_task添加到现有线程
- C++中是否存在 std::conditional 的懒惰等价物?
- 检查某些类型是否是模板类 std::optional 的实例化
- 如何检查两个 std::向量在小于 O(n) 的时间复杂度内是否相等
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- "std::list::splice(std::const_iterator pos, std::list&& other)"是否保证将"其他"留空?
- 为什么程序员同时使用 std::bad_alloc 和 std::exception.是否 std::例外 仅是不够的
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- "using namespace std;"是否免于过多代码规则?
- GCC 或 Clang '-std=' 是否有任何"moving target"别名值,表示"use the latest standard"?