c++ - 从析构函数调用线程 vector

标签 c++ vector copy-constructor stdthread move-constructor

为什么我不能从析构函数中调用我的线程 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/

相关文章:

c++ - 在带有斜杠的路径上返回std::filesystem::create_directories()的值

c++ - 重新检查时指针属性发生变化

c++ - 在 C++ 中对类的 vector 进行排序

c++ - 是否可以使用 C++11 的 for 循环从 vector 中删除?

c++ - 深层复制构造函数 - 类 C++ 中的动态数组无效的 free()/delete/delete[]/realloc()

c++11 - "deleting"C++11 中的复制构造函数/赋值

c# - 30% 的时间解决方案重建失败

c++ - 从 char 数组中提取十六进制数字

c++ - 如果函数参数类型是 ABC,为什么不能按值传递?

c++ - 使用指针复制构造函数