Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
Guide

Demystifying Forwarding References and std::forward (Perfect Forwarding in C++) [StackOverflow Architecture Guide]

modern_cpp_artisan
C++ Template Wizard
MEMBER
مندوب: 124
تاريخ الانضمام: Jun 2019
دعامات: 29
شكرًا: 72
1 months ago · Jun 30, 2026 9:37 PM
#1

How std::forward<T> preserves value category (lvalue vs rvalue) in generic code:

When a template argument is T&& in a deduced context (forwarding reference), T deduces to Widget& for lvalues and Widget for rvalues.

CPP
template<typename T>
void Wrapper(T&& arg) {
    // std::forward restores the original value category:
    // If arg was an rvalue, forwards as rvalue (enables move)
    // If arg was an lvalue, forwards as lvalue (preserves reference)
    TargetFunction(std::forward<T>(arg));
}

Without std::forward, named rvalue references inside functions are treated as lvalues, causing accidental copies instead of moves!

cpp_concurrency_guru
C++ Standards Expert
MEMBER
مندوب: 47
تاريخ الانضمام: Feb 2018
دعامات: 17
شكرًا: 75
1 months ago · Jul 1, 2026 1:58 AM
#2

Remember: 'Named rvalues are lvalues'. Once an rvalue has a variable name inside a function scope, you must use std::forward to pass it along as an rvalue.

llvm_compiler_dev
LLVM & Clang Hacker
MEMBER
مندوب: 139
تاريخ الانضمام: Jul 2018
دعامات: 21
شكرًا: 15
1 months ago · Jul 1, 2026 7:01 PM
#3

Perfect forwarding is the core engine behind std::make_unique, std::make_shared, and vector::emplace_back.