为什么 std::not1() 通过常量引用而不是按值获取参数

Why does std::not1() take parameter by const reference instead of by value?

本文关键字:参数 获取 引用 常量 not1 std 为什么      更新时间:2023-10-16

>std::not1()原型如下:

template< class Predicate >
std::unary_negate<Predicate> not1(const Predicate& pred);

这有效地禁止了移动语义。为什么它没有原型化为:

template< class Predicate >
std::unary_negate<Predicate> not1(Predicate pred);

这样,复制或移动取决于pred的构造方式。然后,该函数只需pred移动到构造的std::unary_negate对象。

单独进行该更改是完全没有用的。not1所做的是使用 pred 作为构造函数的参数来构造一个std::unary_negate<Predicate>。但是std::unary_negate<Predicate>唯一相关的构造函数需要const Predicate &而不是Predicate &&

合乎逻辑的后续问题是,为什么std::unary_negate<Predicate>没有构造函数Predicate &&?在设计时,它显然不可能接受这样的论点,因为右值引用还不存在。至于后来,这有点猜测,但我想说 lambda 已经很好地满足了需求,所以除了向后兼容性之外,unary_negate没有多大意义。