Working with r-value references and link folding can be more complicated than at the beginning.
Excellent call forwarding
The ideal transfer is for the argument provided to the function to be forwarded (passed) to another function with the same category of values ββ(basically r-value vs l-value) as originally provided .
It is usually used with template functions where link folding could occur.
It can also be used within the same function .
Scott Meyers gives the following pseudo-code in his
Going Native 2013 presentation to explain how
std::forward works (approximately 20 minutes);
template <typename T> T&& forward(T&& param) { // T&& here is formulated to disallow type deduction if (is_lvalue_reference<T>::value) { return param; // return type T&& collapses to T& in this case } else { return move(param); } }
Example
Example from the site above, an archetypal example is the make_unique example
template<class T, class... U> std::unique_ptr<T> make_unique(U&&... u) { return std::unique_ptr<T>(new T(std::forward<U>(u)...)); }
In this example, the arguments for unique_ptr provided to him through make_unique , as if they were provided directly in unique_ptr , that is, the reference, l-value and r-value of the nature of the arguments are supported.
A more specific example:
#include <iostream>
short info
Perfect forwarding depends on several fundamental language constructs new to C ++ 11, which form the basis of most of what we now see in general programming:
- Link failed
- Links to Rvalue
- Move semantics
The use of std::forward is currently intended for the formula std::forward<T> , understanding how std::forward works, helps to understand why this is, and also helps to identify non-idiomatic or improper use of rvalues, reducing collapse links and so on .P..
Thomas Becker offers a nice but tight write about the perfect shipping problem and solution.