Perfect Forwarding
Explore how to implement perfect forwarding in C++ by using universal references and std::forward. Understand the challenges of passing arguments by reference, avoid excessive copying, and create generic factory methods that forward arguments correctly while preserving their lvalue or rvalue nature.
A classic problem: A function wants to get its arguments by reference.
For n parameters, 2n function overloads are necessary.
Definition #
If a function template forwards its arguments without changing their lvalue or rvalue characteristics, we call it perfect forwarding.
A perfect factory method #
First, a short disclaimer; the expression, perfect factory method, is not a formal term.
A perfect factory method is a totally generic factory method. In particular, it implies that the function should have the following characteristics:
- takes an arbitrary number of arguments.
- accepts lvalues and rvalues as arguments.
- forwards its arguments in the same way as the underlying constructor.
Let’s describe this in a more formal way. A perfect factory method should be able to create each arbitrary object.
Perfect forwarding enables us to write a function that can identically forward its arguments. The lvalue ...