Developer knowledge network · moderated exchange

UnreliableCode 커뮤니티

개발자 연구, 리버스 엔지니어링 및 코딩 커뮤니티

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개월 전 · 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.