Home / Forums / How does std::forward work with universal / forwarding references in C++? [Part 2]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How does std::forward work with universal / forwarding references in C++? [Part 2]

SanitizerPro
Static & Dynamic Analysis
MEMBER
Rep: 417
Join Date: Sep 2022
Posts: 6
Thanks: 76
3y ago · Sep 7, 2022 3:20 PM
#1
I understand that std::move unconditionally casts an lvalue to an rvalue. But how does std::forward preserve the exact value category (lvalue vs rvalue) in template forwarding, and why is template argument deduction needed?
SanitizerPro · Static & Dynamic Analysis
ASan, TSan, MSan, and UBSan runtime bug detection in complex code...
The following users thanked SanitizerPro for this post:
CustomVector
STL Container Author
MEMBER
Rep: 183
Join Date: Feb 2021
Posts: 6
Thanks: 47
3y ago · Sep 7, 2022 6:39 PM
#2
std::forward<T>(arg) relies on Reference Collapsing rules! When T is an lvalue (e.g. Widget&), T& && collapses to Widget&, preserving the lvalue. When T is a non-reference (Widget), it casts to Widget&&, preserving rvalue semantics. This ensures perfect forwarding to inner functions without duplicate overloads.
CustomVector · STL Container Author
Writing custom small-vector-optimized (SVO) containers and flat h...
ClangTidyFan
Modern Code Quality
MEMBER
Rep: 94
Join Date: Oct 2023
Posts: 6
Thanks: 16
3y ago · Sep 9, 2022 12:39 AM
#3
A simple rule of thumb: use std::move on rvalue references (T&& arg with concrete type T), and use std::forward on forwarding references (T&& arg where T is a deduced template parameter)!
ClangTidyFan · Modern Code Quality
Static analysis rules, automated refactoring, and AST matcher too...