CKTIS / C++
Lvalue reference: T&
A T& reference aliases an object or a function without making a copy. It cannot be reseated after initialization. For object types, const T& restricts modification through the reference and can also bind to a suitable temporary object.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
T& name = object;
const T& name = expression;A T& declaration creates an lvalue reference; && denotes a distinct rvalue-reference type. For an object, think of a reference as another name, not a copy. In int& ref = value;, operations on ref affect value. A local reference variable requires an initializer; a well-defined program does not use a reference as a nullable pointer substitute.
For an unqualified object type T, T& normally binds to a compatible, modifiable lvalue. int& ref = 7; is ill-formed. const T& also accepts const objects and suitable temporary values. Here const qualifies access to the object: it prevents modifying an ordinary object through this reference, but does not freeze an object accessible through another mutable alias.
A reference cannot be reseated after initialization. In the example, ref = other; assigns a value to value; the later ++other does not change value. A T& parameter lets a function modify the caller's object; const T& provides read-only access without copying when binding directly to an existing object.
A reference can dangle when its object's lifetime ends. The local declaration const int& temporary = 7; extends the temporary object's lifetime to that of the reference. Do not generalize this rule: a temporary bound to a reference parameter lasts only until the end of the full-expression containing the call. Do not return a reference to an ordinary local variable.
Examples
#include <iostream>
int main() {
int value = 10;
int other = 20;
int& ref = value;
const int& view = value;
const int& temporary = 7;
ref += 5;
std::cout << value << ' ' << view << '\n';
ref = other;
++other;
std::cout << value << ' ' << ref << ' ' << other << '\n';
std::cout << temporary << '\n';
}
Result
15 15 20 20 21 7
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.