std::for_each 不可复制对象向量

std::for_each over a vector of non-copyable objects

我在 cppreference 中阅读有关 std::for_each 的内容:

Unlike the rest of the parallel algorithms, for_each is not allowed to make copies of the elements in the sequence even if they are trivially copyable.

所以,对我来说,这意味着 std::for_each 不会在容器中复制构造对象,它应该可以很好地处理不可复制对象的容器。但是在尝试使用 VS2015 编译此代码时:

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

   std::for_each(
      threads.begin(), 
      threads.end(), 
      [threads](std::thread & t) {t.join(); });

编译器抱怨 cctor 被删除:

Error   C2280   'std::thread::thread(const std::thread &)': attempting to reference a deleted function ... 

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

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

试试这个:

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

std::for_each(threads.begin(), threads.end(), [](std::thread & t){t.join();});