Dylan B. answered 11/10/20
Computer science Tutor, Associates degree, Real world experience
There are a number of good posts on what std::forward
does and how it works (such as here and here).
In a nutshell, it preserves the value category of its argument. Perfect forwarding is there to ensure that the argument provided to a function is forwarded to another function (or used within the function) with the same value category (basically r-value vs. l-value) as originally provided. It is typically used with template functions where reference collapsing may have taken place (involving universal/forwarding references).
Consider the code sample below. Removing the std::forward
would print out requires lvalue
and adding the std::forward
prints out requires rvalue
. The func
is overloaded based on whether it is an rvalue or an lvalue. Calling it without the std::forward
calls the incorrect overload. The std::forward
is required in this case as pass
is called with an rvalue.