Perfect Forwarding

suggest change

Remarks

Perfect forwarding requires forwarding references in order to preserve the ref-qualifiers of the arguments. Such references appear only in a deduced context. That is:

template<class T>
void f(T&& x) // x is a forwarding reference, because T is deduced from a call to f()
{
    g(std::forward<T>(x)); // g() will receive an lvalue or an rvalue, depending on x
}

The following does not involve perfect forwarding, because T is not deduced from the constructor call:

template<class T>
struct a
{
    a(T&& x); // x is an rvalue reference, not a forwarding reference
};

C++17 class template argument deduction synthesizes a deduction guide from that constructor. In that implicit guide, T&& is still not a forwarding reference, because T is a template parameter of the class template:

a example1(1);
  // same as a<int> example1(1);

int x = 1;
a example2(x);
  // error: deduces a<int>, and int&& cannot bind to the lvalue x

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents