Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

In the book "Effective modern C++", at the item 3 there is written this piece of code:

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

I don't understand why you call std::forward? If c is an rvalue reference, what does it change to call the operator[] on a rvalue instead on a lvalue? For me c[i] should be enough.

PS: I understand the purpose of std::forward when the variable is a parameter of a function as:

template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
  return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
like image 395
cheval celeste Avatar asked Mar 26 '16 23:03

cheval celeste


1 Answers

It’s possible that operator[] for Container has been overloaded for rvalues and lvalues.

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

If so, we want to make sure that if c was initialized with an rvalue, we call the rvalue version of operator[] on c. It’s certainly not common to overload operator[] to behave differently for lvalues and rvalues, but it’s possible, so in truly generic code, we need to apply std::forward to c before forwarding it to operator[].

like image 129
Thomas Avatar answered Sep 30 '22 02:09

Thomas