容器调用运算符[]上的c++std::forward

c++ std::forward on the container calling operator[]

本文关键字:上的 c++std forward 调用 运算符      更新时间:2023-10-16

在《有效的现代C++》一书中,在第3项中有这样一段代码:

template<typename Container, typename Index>
decltype(auto)
authAndAccess(Container&& c, Index i)
{
  authenticateUser();
  return std::forward<Container>(c)[i];
}

我不明白你为什么叫std::forward?如果c是右值引用,那么在右值上而不是在左值上调用operator[]会有什么变化?对我来说c[i]应该足够了。

PS:当变量是函数的参数时,我理解std::forward的用途为:

template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
  return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}

Container的运算符[]可能已经重载了右值和左值。

auto Container::opeartor[](int i) && -> Container::value_type&;
auto Container::opeartor[](int i) & -> Container::value_type&;

如果是这样的话,我们想确保如果c是用右值初始化的,我们在c上调用运算符[]的右值版本。重载运算符[]对左值和右值的行为不同当然是不常见的,但这是可能的,所以在真正的泛型代码中,我们需要在将其转发给运算符[]之前将std::forward应用于c。