Site Tools


wiki:cpp-perfect-forwarding

Table of Contents

C++ Perfect forwarding

Perfect forwarding 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.

// 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;
}
wiki/cpp-perfect-forwarding.md · Last modified: by 127.0.0.1