为什么下面的代码不能编译?
#include <future>
#include <numeric>
#include <vector>
int main() {
const std::vector<int> values{1, 2, 3, 4, 5};
auto futures = std::accumulate(
begin(values), end(values), std::vector<std::future<int>>{},
[](auto accumulator, auto value) {
accumulator.push_back(
async(std::launch::async, [value] { return value; }));
return accumulator;
});
}
https://cpp.godbolt.org/z/c967ra1hY
有趣的是,使用 cppreference 中的accumulate 实现作品https://cpp.godbolt.org/z/MdM8Wh3Eq .
最佳答案
这是 std::accumulate
规范中的缺陷。该算法被指定为将累加器重复复制到 binary_op
参数中。这是changed C++20 中的重复移动。因此,与旧标准相比,C++20 中的标准库实现表现出不同的行为,如您所见 here (来自第 31 行)在 MSVC 的示例中。
这就是在 C++20 之前破坏代码的原因,因为 std::future
的 std::vector
是不可复制的。因此添加编译器开关/std:c++20
。如果您坚持使用较旧的标准,那么您可能会不走运,即使这并不是您的错。
关于C++ 如何 std::accumulate future vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75635355/