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.