Std::fill_n的右值,是否只支持复制填充

std::fill_n of rvalues, does it only support filling by copy?

本文关键字:是否 支持 复制 填充 fill Std      更新时间:2023-10-16

给定std::futuresstd::vector

std::vector<std::future<void>> futures;

为什么std::fill_n抱怨我在传递右值时调用复制构造函数:

std::fill_n(std::back_inserter(futures), 10, std::async([]{ std::cout << "yon"; }));
error: use of deleted function future(const future&)

我的意思是,fill_n不接收一个xvalue?如果没有,为什么不呢?

std::fill_n复制作为第三个参数传递的给定对象,但第三个参数是不可复制的未来对象,因为复制未来没有意义。因此出现了错误。

你似乎需要这个:

std::generate_n(std::back_inserter(futures), 
                10, 
               []{  return std::async([]{ std::cout << "yon"; }); });

std::fill_n的接口为:

template< class OutputIt, class Size, class T >
OutputIt fill_n( OutputIt first, Size count, const T& value );

然后复制value count次。这就是你得到错误的原因。虽然,即使它移动,fill_n作为功能的选择也没有意义……你会从同一个future移动10次,所以你最终会得到一个有效的future和9个空的?那有什么意义呢?