我正在阅读 std::for_each
在 cppreference :
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 捕获 block 尝试按值捕获整个 vector 。这是不必要的,因为对元素的访问是通过引用参数授予的。
试试这个:
std::vector<std::thread> threads;
std::for_each(threads.begin(), threads.end(), [](std::thread & t){t.join();});
关于c++ - std::for_each 在不可复制对象的 vector 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698497/