c++ std::forward 在容器上调用 operator[]

che*_*ste 5 c++

在《Effective modern C++》一书中,在第3项中写了这段代码:

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

我不明白你为什么打电话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)...));
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 4

\xe2\x80\x99s Container 的operator[] 可能已针对右值和左值重载。

\n\n
auto Container::opeartor[](int i) && -> Container::value_type&;\nauto Container::opeartor[](int i) & -> Container::value_type&;\n
Run Code Online (Sandbox Code Playgroud)\n\n

如果是这样,我们要确保如果 c 是用右值初始化的,则我们在 c 上调用 operator[] 的右值版本。重载operator[]以对左值和右值表现不同的情况当然不常见,但它是可能的,所以在真正的通用代码中,我们需要在c之前应用std::forward将其转发给操作员[]。

\n