CKTIS / C++
Rvalue reference: T&&
T&& declares an rvalue reference, a type distinct from T&. It binds to suitable rvalues and participates in move semantics. A reference name used as an expression is normally an lvalue. In C++23, however, a move-eligible name is an xvalue, as when the name of an rvalue-reference parameter referring to a non-volatile object type is used directly as the operand of a return statement. T&& with a deduced template parameter can be a forwarding reference.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
T&& name = expression;
void consume(T&& value);
template<class T> void relay(T&& value);For a fixed, non-reference object type T, T&& denotes an rvalue reference; T& denotes the distinct lvalue reference type. For example, int&& r = 7; binds r to a temporary object. An int&& cannot bind directly to an int lvalue. A local reference definition requires initialization. Later assignment changes the referred-to object, not which object the reference denotes.
A declaration's type and an expression's value category are different things. In the example, r has declared type int&&, but the expression r is an lvalue. Consequently, inspect(r) selects int&, whereas inspect(std::move(r)) selects int&&. std::move exposes an expression as an xvalue; it does not itself transfer resources. A subsequently selected constructor or assignment operator may perform a move.
Not every T&& is an ordinary rvalue-only parameter. In template<class T> void relay(T&& value);, when T is deduced from the call argument, it is a forwarding reference: it accepts lvalues and rvalues. For an int lvalue argument, T is deduced as int&, and reference collapsing produces int&. The collapsing rule is: only && combined with && yields &&; all other combinations yield &. A const T&& parameter is not a forwarding reference. Use std::forward<T>(value) for onward forwarding.
A reference does not guarantee that its object still exists. Directly binding a temporary in int&& r = 7; extends its lifetime to the lifetime of the local reference. However, a temporary bound to a reference parameter lasts only until the end of the full-expression containing the call. Retaining that reference does not extend the object's lifetime again and can leave a dangling reference.
Examples
#include <iostream>
#include <utility>
void inspect(int&) {
std::cout << "lvalue\n";
}
void inspect(int&&) {
std::cout << "rvalue\n";
}
int main() {
int&& r = 7;
inspect(r);
inspect(std::move(r));
inspect(9);
r = 12;
std::cout << r << '\n';
}
Result
lvalue rvalue rvalue 12
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.