std::for_each 在不可复制对象的向量上

Gup*_*pta 1 c++ language-lawyer

std::for_eachcppreference中阅读:

与其他并行算法不同,for_each 不允许复制序列中的元素,即使它们是可复制的。

所以,对我来说,这意味着std::for_each不会在容器中复制构造对象,它应该可以与不可复制对象的容器一起正常工作。但是在尝试使用 VS2015 编译此代码时:

   std::vector<std::thread> threads;

   std::for_each(
      threads.begin(), 
      threads.end(), 
      [threads](std::thread & t) {t.join(); });
Run Code Online (Sandbox Code Playgroud)

编译器抱怨要删除的 cctor:

Error   C2280   'std::thread::thread(const std::thread &)': attempting to reference a deleted function ... 
Run Code Online (Sandbox Code Playgroud)

我对上述引用的理解有什么问题?

Jak*_*kuJ 7

您的 lambda 捕获块尝试按值捕获整个向量。这是不必要的,因为对元素的访问是通过引用参数授予的。

尝试这个:

std::vector<std::thread> threads;

std::for_each(threads.begin(), threads.end(), [](std::thread & t){t.join();});
Run Code Online (Sandbox Code Playgroud)