Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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 месяцев назад · 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 месяцев назад · 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 месяцев назад · Jul 1, 2026 7:01 PM
#3

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