Binds a reference to an object.
Syntax
Non-list-initializationT&ref=target;T&ref(target);
(1) T&&ref=target;T&&ref(target);
(2) (since C++11)func-refpar(target)(3) returntarget;(4) (inside the definition of func-refret )Class::Class(...) :ref-member(target) { ... }(5) (inside the definition of Class )Ordinary list-initialization (since C++11)T&ref= {arg1,arg2, ... };T&ref{arg1,arg2, ... };
(1) T&&ref= {arg1,arg2, ... };T&&ref{arg1,arg2, ... };
(2) func-refpar({arg1,arg2, ... });(3) Designated list-initialization (since C++20)T&ref= {.des1=arg1, .des2{arg2} ... };T&ref{.des1=arg1, .des2{arg2} ... };
(1) T&&ref= {.des1=arg1, .des2{arg2} ... };T&&ref{.des1=arg1, .des2{arg2} ... };
(2) func-refpar({.des1=arg1, .des2{arg2} ... });(3) A reference to T can be initialized with an object of type T, a function of type T, or an object implicitly convertible to T. Once initialized, a reference cannot be reseated (changed) to refer to another object.
References are initialized in the following situations:
1) When a named
variable is declared with an initializer.
2) When a named
variable is declared with an initializer.
3) In a function call expression, when the function parameter has reference type.
4) In the return statement, when the function returns a reference type. The program is ill-formed if the returned reference is bound to the result of a
.(since C++26)
Explanation
T- the referenced type ref- the reference variable to be initialized target- the initializer expression being used func-refpar- a function with a parameter of reference type (T& or T&&(since C++11)) func-refret- a function whose returns type is a reference type (T& or T&&(since C++11)) Class- a class name ref-member- a non-static data member of reference type (T& or T&&(since C++11)) of Classdes1, des2, ... - designators arg1, arg2, ... - the initializers in initializer lists Definitions
For two types T1 and T2:
Given the cv-unqualified versions of T1 and T2 as U1 and U2 respectively, if U1 is
to U2, or U1 is a
of U2, T1 is reference-related to T2.
If a prvalue of type “pointer to T2” can be converted to the type “pointer to T1” via a standard conversion sequence, T1 is reference-compatible with T2.
Initialization rules
If a reference initialization uses an ordinary or designated(since C++20) list-initialization, the rules of
are followed.
(since C++11)For non-list reference initialization, given the type of target as U, the reference either binds directly to target or binds to a value of type T converted from target. Direct binding is considered first, followed by indirect binding, if neither binding is available, the program is ill-formed.
In all cases where the reference-compatible relationship of two types is used to establish the validity of a reference binding and the standard conversion sequence would be ill-formed, a program that necessitates such a binding is ill-formed.
Direct binding
If all following conditions are satisfied:
The reference to be initialized is an lvalue reference.
target is a non-
lvalue.
T is reference-compatible with U.
Then the reference binds to target, or to its appropriate base class subobject:
doubled=2.0;double&rd=d;// rd refers to dconstdouble&rcd=d;// rcd refers to dstructA{};structB:A{}b;A&ra=b;// ra refers to A subobject in bconstA&rca=b;// rca refers to A subobject in bOtherwise, if all following conditions are satisfied:
The reference to be initialized is an lvalue reference.
U is a class type.
T is not reference-related to U.
target can be converted to an lvalue of type V such that T is reference-compatible with V.
Then the reference binds to the lvalue result of the conversion, or to its appropriate base class subobject:
structA{};structB:A{operatorint&();};int&ir=B();// ir refers to the result of B::operator int&Otherwise, if the reference to be initialized is an lvalue reference, and T is not const-qualified or is volatile-qualified, the program is ill-formed:
double&rd2=2.0;// error: not an lvalue and reference is not constinti=2;double&rd3=i;// error: type mismatch and reference is not constOtherwise, if all following conditions are satisfied:
target is a value of any following category:
rvalue
(until C++11)non-bit-field xvalue
class prvalue
array prvalue
function lvalue
(since C++11)
(until C++17)non-bit-field rvalue
function lvalue
(since C++17)T is reference-compatible with U.
Then the reference binds to target, or to its appropriate base class subobject:
structA{};structB:A{};externBf();constA&rca2=f();// bound to the A subobject of the B rvalue.A&&rra=f();// same as aboveinti2=42;int&&rri=static_cast<int&&>(i2);// bound directly to i2If target is a prvalue,
is applied to it, considering the type of the prvalue to be the adjusted type P.
P is
from the type of target (i.e. U) by adding the cv-qualification of T to it.
In this case, the reference binds to the result object, or to its appropriate base class subobject.
(since C++17)Otherwise, if all following conditions are satisfied:
U is a class type.
T is not reference-related to U.
target can be converted to a value v of type V such that T is reference-compatible with V, where v is of any following category:
rvalue
(until C++11)xvalue
class prvalue
function lvalue
(since C++11)
(until C++17)rvalue
function lvalue
(since C++17)Then the reference binds to the result of the conversion, or to its appropriate base class subobject:
structA{};structB:A{};structX{operatorB();}x;constA&r=x;// bound to the A subobject of the result of the conversionB&&rrb=x;// bound directly to the result of the conversionIf the result of the conversion is a prvalue,
is applied to it, considering the type of the prvalue to be the adjusted type P.
P is
from the type of the conversion result by adding the cv-qualification of T to it.
In this case, the reference binds to the result object, or to its appropriate base class subobject.
(since C++17)Indirect binding
If direct binding is not available, indirect binding is considered. In this case, T cannot be reference-related to U.
If T or U is a class type, user-defined conversions are considered using the rules for
of an object of type T by user-defined conversion. The program is ill-formed if the corresponding non-reference copy-initialization would be ill-formed. The result of the call to the conversion function, as described for the non-reference
, is then used to direct-initialize the reference. For this direct-initialization, user-defined conversions are not considered.
Otherwise, a temporary of type T is created and copy-initialized from target. The reference is then bound to the temporary.
(until C++17)Otherwise, target is implicitly converted to a prvalue of type “cv-unqualified T”. The temporary materialization conversion is applied, considering the type of the prvalue to be T, and the reference is bound to the result object.
(since C++17)conststd::string&rs="abc";// rs refers to temporary copy-initialized from char arrayconstdouble&rcd2=2;// rcd2 refers to temporary with value 2.0inti3=2;double&&rrd3=i3;// rrd3 refers to temporary with value 2.0Lifetime of a temporary
Whenever a reference is bound to a temporary object or to a subobject thereof, the lifetime of the temporary object is extended to match the lifetime of the reference (check
temporary object lifetime exceptions
), where the temporary object or its subobject is denoted by one of following expression:
a parenthesized expression (e), where e is one of these expressions,
a
of form a[n] or n[a], where a is an array and is one of these expressions,
a
class member access expression
of form e.m, where e is one of these expressions and m designates a non-static data member of object type,
a
of form e.*mp, where e is one of these expressions and mp is a pointer to data member,
a
,
,
, or
conversion without a user-defined conversion that converts one of these expressions to the glvalue refers to the object designated by the operand, or to its complete object or a subobject thereof (an
expression is interpreted as a sequence of these casts),
a
of form cond?e1:e2 that is a glvalue, where e1 or e2 is one of these expressions, or
a
of form x,e that is a glvalue, where e is one of these expressions.
There are following exceptions to this lifetime rule:
a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such return statement always returns a dangling reference.
(until C++26)a temporary bound to a reference parameter in a function call exists until the end of the full expression containing that function call: if the function returns a reference, which outlives the full expression, it becomes a dangling reference.
a temporary bound to a reference in the initializer used in a new-expression exists until the end of the full expression containing that new-expression, not as long as the initialized object. If the initialized object outlives the full expression, its reference member becomes a dangling reference.
(since C++11)a temporary bound to a reference in a reference element of an aggregate initialized using
syntax (parentheses) exists until the end of the full expression containing the initializer, as opposed to
syntax {braces}.
structA{int&&r;};Aa1{7};// OK, lifetime is extendedAa2(7);// well-formed, but dangling reference(since C++20)In general, the lifetime of a temporary cannot be further extended by "passing it on": a second reference, initialized from the reference variable or data member to which the temporary was bound, does not affect its lifetime.
Notes
References appear without initializers only in function parameter declaration, in function return type declaration, in the declaration of a class member, and with the
specifier.
Until the resolution of
, a temporary is permitted to bound to a reference member in a constructor
, and it persists only until the constructor exits, not as long as the object exists. Such initialization is ill-formed since
, although many compilers still support it (a notable exception is clang).
Example
Run this code
#include<sstream>#include<utility>structS{intmi;conststd::pair<int,int>∓// reference member};voidfoo(int){}structA{};structB:A{intn;operatorint&(){returnn;}};Bbar(){returnB();}//int& bad_r; // error: no initializerexternint&ext_r;// OKintmain(){// Lvaluesintn=1;int&r1=n;// lvalue reference to the object nconstint&cr(n);// reference can be more cv-qualifiedvolatileint&cv{n};// any initializer syntax can be usedint&r2=r1;// another lvalue reference to the object n// int& bad = cr; // error: less cv-qualifiedint&r3=const_cast<int&>(cr);// const_cast is neededvoid(&rf)(int)=foo;// lvalue reference to functionintar[3];int(&ra)[3]=ar;// lvalue reference to arrayBb;A&base_ref=b;// reference to base subobjectint&converted_ref=b;// reference to the result of a conversion// Rvalues// int& bad = 1; // error: cannot bind lvalue ref to rvalueconstint&cref=1;// bound to rvalueint&&rref=1;// bound to rvalueconstA&cref2=bar();// reference to A subobject of B temporaryA&&rref2=bar();// sameint&&xref=static_cast<int&&>(n);// bind directly to n// int&& copy_ref = n; // error: can't bind to an lvaluedouble&©_ref=n;// bind to an rvalue temporary with value 1.0// Restrictions on temporary lifetimes// std::ostream& buf_ref = std::ostringstream() << 'a';// the ostringstream temporary was bound to the left operand// of operator<< but its lifetime ended at the semicolon so// the buf_ref is a dangling referenceSa{1,{2,3}};// temporary pair {2, 3} bound to the reference member// a.mp and its lifetime is extended to match // the lifetime of object aS*p=newS{1,{2,3}};// temporary pair {2, 3} bound to the reference// member p->mp, but its lifetime ended at the semicolon// p->mp is a dangling referencedeletep;// Imitate [[maybe_unused]] applied to the following variables:[](...){}(cv,r2,r3,rf,ra,base_ref,converted_ref,a,cref,rref,cref2,rref2,copy_ref,xref);}Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR Applied to Behavior as published Correct behavior
C++98 initialize a reference to const-qualified type with a class type
rvalue might create a temporary, and a constructor of that class
was required in order to copy the rvalue into that temporary no temporary is
created, constructor
is not required
C++98 a reference to const-qualified array could not be
initialized with a reference-compatible array rvalue allowed
C++98 a reference could not bind directly to an array or class rvalue allowed
C++98 a reference to const-qualified type initialized with a type which is not
reference-compatible but has a conversion function to a reference-
compatible type was bound to a temporary copied from the return
value (or its base class subobject) of the conversion function bound to the return
value (or its base class
subobject) directly
C++11 the conversion from target of class type to another
reference-compatible type could only be implicit allow explicit
conversions
C++11 a reference could bind to a bit-field xvalue prohibited
C++98 the definition of temporary was unclear made clear
C++98 user-defined conversions in indirect
binding did not consider the type of targetconsidered
C++98 user-defined conversions were not considered in indirect binding considered
C++98 reference compatibility did not consider qualification conversions considered
C++17 cv-qualification was not added to the result type
of temporary materialization in indirect binding added
C++17 cv-qualification was not added to the result type
of temporary materialization in direct binding added
C++98 reference-related types were allowed for indirect binding prohibited See also