为什么std :: not1()通过const引用而不是值来获取参数?

Lin*_*gxi 4 c++ c++-standard-library language-lawyer

std::not1() 原型如下:

template< class Predicate >
std::unary_negate<Predicate> not1(const Predicate& pred);
Run Code Online (Sandbox Code Playgroud)

这有效地禁止了移动语义.为什么不将它原型化为:

template< class Predicate >
std::unary_negate<Predicate> not1(Predicate pred);
Run Code Online (Sandbox Code Playgroud)

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

小智 5

单独进行这种改变是完全没用的.什么not1是构造一个std::unary_negate<Predicate>using pred作为构造函数的参数.但是,唯一相关的构造std::unary_negate<Predicate>需要const Predicate &,不是 Predicate &&.

合乎逻辑的后续问题是,为什么没有std::unary_negate<Predicate>构造函数采取Predicate &&?它在设计时显然不可能采用这样的论证,因为右值参考尚不存在.至于后来,这是一个猜测,但我会说lambdas已经很好地满足了需求,所以unary_negate除了向后兼容之外,没有太多的意义了.