Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using std::forward on container before accessing element?

Scott Meyers in his new book "Effective Modern C++" shows the following function as an example of using decltype(auto) (page 28):

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

My question is simple. Why do we need std::forward applied to c here? We are not passing c anywhere, we are calling operator[] on it. And none of standard containers have ref-qualified overloads (r-value/l-value overloads) of operator[].

So I see only two reasons for this std::forward:

  1. To account for potential containers which implement ref-qualified overloads of operator[].
  2. For consistency: whenever a variable declared as forwarding (universal) reference is used, apply std::forward on it. Period.

Any other reasons?

like image 673
Mikhail Avatar asked Dec 15 '14 16:12

Mikhail


1 Answers

Reason #1 is the relevant one. When you implement a generic function, you don't go by "What do these particular types I know about do?", but by "What do I know about the generic thing I am working with?".

The generic container doesn't say anything about reference qualification, so you forward.

Of course, reason #2 is much easier to remember and reason about, so you should follow that.

I don't think there are any other reasons.

like image 163
Sebastian Redl Avatar answered Nov 07 '22 01:11

Sebastian Redl