为什么 std::not1() 通过 const 引用而不是值来获取参数?
Why does std::not1() take parameter by const reference instead of by value?
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
除了向后兼容之外没有太多意义了。
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
除了向后兼容之外没有太多意义了。