c++ - std::for_each 在不可复制对象的 vector 上

标签 c++ language-lawyer

我正在阅读 std::for_eachcppreference :

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/

相关文章:

c++ - 征求有关数据结构使用的建议

c++ - 运算符重载以构造异常消息

c++ - 向我介绍 boost::exception

c++ - bash : ./main: 无法执行二进制文件: Exec 格式错误

c++ - decltype 类内定义函数的扣除结果

c++ - 两个无符号短裤的乘法真的会导致未定义的行为吗?

c++ - 为什么 C++11 包含一个关于比较 void 指针的奇怪子句?

c++ - `push_back` 与 `emplace_back` 标志警告

c++ - 预递增字符串文字

c++ - 在 Win32 中使用 IShellLinkA 和 IPersistFile 创建文件快捷方式时生成的 Unicode 文件名