【问题标题】:Calling vector of threads from destructor从析构函数调用线程向量
【发布时间】:2019-12-01 14:18:28
【问题描述】:

为什么我不能从析构函数中调用我的线程向量?使用析构函数有什么规则吗?

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'的私有构造函数

【问题讨论】:

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


    【解决方案1】:

    问题出在:

    VecThreads h = VecThreads();
    

    VecThreads 没有移动构造函数,它的生成被禁用(即,未声明),因为它有一个用户定义的析构函数。因此,上面的语句调用了VecThreads 的复制构造函数。

    VecThreads 包含一个std::vector&lt;std::thread&gt; 类型的数据成员——它不可复制,因为std::thread 对象不可复制。尽管std::vector&lt;std::thread&gt; 不可复制,但它是可移动的,因此移动构造函数原则上可以解决问题。您可以通过在VecThreads 的定义中添加以下内容来显式启用移动构造函数的生成:

    VecThreads(VecThreads&&) = default;
    

    由于强制复制省略,您的原始代码无需修改即可从 C++17 编译。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-22
      • 2014-08-22
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 2012-02-12
      • 2016-03-20
      • 1970-01-01
      相关资源
      最近更新 更多