The place where random ideas get written down and lost in time.
2023-10-16 - C++ “r-value reference T&&”
Category DEVTrying to make any sense of the “T&&” notation in C++.
It means “an r-value reference” “a forwarding reference”.
https://stackoverflow.com/questions/4549151/c-double-address-operator
https://stackoverflow.com/questions/5481539/what-does-t-double-ampersand-mean-in-c11 (*)
It’s referenced in the C++11 “range-based for loop” loop construct:
https://en.cppreference.com/w/cpp/language/range-for
for (auto&& [first, second] : mymap) { … } ← WAT?
The summary of the SO (*) above is:
- rvalue is the result of an expression or any temporary (e.g. type conversion).
- Typically, it would be used as a “copy” using a “const T&” reference and becomes an lvalue. E.g. the user cannot modify the value (since it becomes const).
- T&& is used as a receiving argument type in a function.
- An argument of “T&&” preserves (forwards) the “rvalue” property and passes it down as-is. The user can modify the value (since it is not const).
- When used in a template, “T&&” becomes either “T&” (for an lvalue), or “T” (for an rvalue / temporary).
- As such it’s named a “forwarding reference” and is associated with std::forward<T>.
About std::forward<>, it’s equivalent to performing a static cast of “T&&” to preserve its rvalue:
Coming back to that “range-based for loop” construct:
https://en.cppreference.com/w/cpp/language/range-for
- for (auto x : array) {} → access by value (I guess “copy”)
- for (const T& x : array) {} → access by const reference
- for (auto&& x : array) {} → access by “forwarding reference” (not const)
are all possible.