liveBook · Manning

Perfect forwarding

As explained in Learn C++ by Example

Perfect forwarding is a C++ technique for passing arguments through a wrapper while preserving their original value categories and cv-ref qualifiers.

Perfect forwarding passes arguments through a wrapper while preserving their original value categories and cv-ref qualifiers. With vectors, it helps construct elements without copying temporary row data. section 2.2.3

The vector example distinguishes the relevant operations:

  • push_back accepts a complete object; its const-reference overload copies the supplied row. section 2.2.3
  • The rvalue-reference overload accepts a temporary and can move its elements instead of copying them. section 2.2.3
  • emplace_back constructs the vector element in place from the temporary row. section 2.2.3

Generating a triangle without copying rows

generate_triangle initializes the first row, then calls get_next_row(triangle.back()) and passes the temporary directly to triangle.push_back. The alternative triangle.emplace_back(get_next_row(triangle.back())) constructs the row in place.

How Learn C++ by Example covers it

How deep it goes
Explains lvalues, rvalues, overloads, moving, and emplacement, but defers other value categories and full language details.
Examples
Demonstrates triangle generation with temporary rows, push_back overloads, vector move construction, and emplace_back.
What you can do after
Apply it via std::vector push_back and emplace_back to avoid copying temporary rows.
How it connects
Connects perfect forwarding with move semantics, rvalue references, lvalues, rvalues, std::vector, push_back, and emplace_back.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.