为什么不能从析构函数调用线程向量?是否有使用析构函数的规则?
void p ()
{
std::cout << "thread running " << std::endl;
}
class VecThreads // Error: In instantiation of member function 'std::__1::vector<std::__1::thread, std::__1::allocator<std::__1::thread> >::vector' requested here
{
public:
std::vector<std::thread> threads;
VecThreads() {
threads.push_back(std::thread(p));
}
~VecThreads()
{
threads[0].join();
}
};
int main(int argc, const char * argv[]) {
VecThreads h = VecThreads();
//h.threads[0].join(); // delete deconstructor and use this works fine
return 0;
}
我得到的错误:
调用类'std :: __ 1 :: thread'的私有构造函数
问题出在:
VecThreads h = VecThreads();
VecThreads
没有move构造函数,因为它具有用户定义的destructor,所以禁用了它的生成(即未声明)。因此,以上语句调用的副本构造函数。VecThreads
VecThreads
包含类型为数据的成员std::vector<std::thread>
–由于std::thread
对象不可复制,因此不可复制。即使anstd::vector<std::thread>
不可复制,它也是可移动的,因此从原理上讲,move构造函数可以解决问题。您可以通过在内部VecThreads
的定义中添加以下内容来显式启用move构造函数的生成:
VecThreads(VecThreads&&) = default;
自从C ++ 17起,您的原始代码就可以编译,无需进行任何修改,这要归功于必需的复制省略。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句