skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-perfect-forwarding
This page is read only. You can view the source, but not change it.
# C++ perfect forwarding **[Perfect forwarding](https://en.cppreference.com/w/cpp/language/reference#Forwarding_references)** is the technique of using forwarding references and `std::forward` to write a template function that accepts arguments and passes them to another function while preserving their value categories (lvalue vs. rvalue). This avoids unnecessary copies and ensures move operations happen when appropriate. Use perfect forwarding in wrapper functions, factory functions, and generic utilities that delegate to other functions. ## Example This example shows perfect forwarding preserving argument categories through multiple function calls. ```cpp // compile: g++ -std=c++17 -o perfect perfect.cpp // run: ./perfect // description: perfect forwarding preserves lvalue/rvalue through delegation #include <iostream> #include <utility> #include <memory> void process(const int& x) { std::cout << "Process lvalue: " << x << "\n"; } void process(int&& x) { std::cout << "Process rvalue: " << x << "\n"; } template <typename T> void wrapper(T&& arg) { process(std::forward<T>(arg)); // perfect forward } int main() { int x = 42; wrapper(x); // forwards as lvalue wrapper(100); // forwards as rvalue return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top