[C ++] Universal reference and perfect forwarding

Universal Reference
template<typename T>
void func(T&& param) {
    cout << param << endl;
}

Formal parameters using the T && type can bind both rvalues ​​and lvalues.

But note: only when type deduction occurs, T && means universal reference; otherwise, it means rvalue reference.

Reference Collapse

The universal reference is finished, then let's talk about Reference Collapse, because the concept of Perfect Forwarding involves reference folding. A template function, according to the defined formal parameters and the types of incoming actual parameters, we can have the following four combinations:

  • Lvalue-Lvalue T & & # The formal parameter type defined by the function is an lvalue reference, and the actual parameter passed in is an lvalue reference
  • Lvalue-rvalue T & && # The formal parameter type defined by the function is an lvalue reference, and the actual parameter passed in is an rvalue reference
  • Rvalue-lvalue T && & # The formal parameter type defined by the function is an rvalue reference, and the actual parameter passed in is an lvalue reference
  • Rvalue-rvalue T && && # The formal parameter type defined by the function is an rvalue reference, and the actual argument passed in is an rvalue reference

However, C ++ is not allowed to quote again, and there are the following rules for the treatment of the above situation:

All folded references ultimately represent a reference, either an lvalue reference or an rvalue reference. The rule is: if any reference is an lvalue reference, the result is an lvalue reference. Otherwise (that is, both are rvalue references), the result is an rvalue reference.

That is, the first three cases represent lvalue references, while the fourth represents rvalue references.

Perfect Forwarding

Keep the variable type unchanged during the function call? This is what we call the "perfect forwarding" technology, which is implemented in C ++ 11 through the std :: forward () function.

template<typename T>
void warp(T&& param) {
    func(std::forward<T>(param));
}
Published 431 original articles · Liked 14 · Visitors 100,000+

Guess you like

Origin blog.csdn.net/LU_ZHAO/article/details/105503372