为什么我不能从析构函数中调用我的线程 vector ?使用析构函数有什么规则吗?
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;
}
我得到的错误:
Calling a private constructor of class 'std::__1::thread'
最佳答案
问题出在:
VecThreads h = VecThreads();
VecThreads
没有移动构造函数,它的生成被禁用(即,未声明)因为它有一个用户定义的析构函数。因此,上面的语句调用VecThreads
的复制构造函数。
VecThreads
包含 std::vector<std::thread>
类型的数据成员– 自 std::thread
以来不可复制对象不可复制。即使 std::vector<std::thread>
不可复制,它是可移动的,因此移动构造函数原则上可以解决问题。您可以通过在 VecThreads
中添加以下内容来显式启用移动构造函数的生成的定义:
VecThreads(VecThreads&&) = default;
由于强制复制省略,您的原始代码自 C++17 起无需修改即可编译。
关于c++ - 从析构函数调用线程 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59126363/