On this page
Reference declaration
Declares a named variable as a reference, that is, an alias to an already-existing object or function.
Syntax
A reference variable declaration is any simple declaration whose declarator has the form
& attr (optional) declarator |
(1) | |
&& attr (optional) declarator |
(2) | (since C++11) |
S& D;
declares D
as an lvalue reference to the type determined by decl-specifier-seq S
.
S&& D;
declares D
as an rvalue reference to the type determined by decl-specifier-seq S
.
declarator | - | any declarator except another reference declarator (there are no references to references) |
attr | - | (since C++11) list of attributes |
A reference is required to be initialized to refer to a valid object or function: see reference initialization.
The type “reference to (possibly cv-qualified) void” cannot be formed.
Reference types cannot be cv-qualified at the top level; there is no syntax for that in declaration, and if a qualification is added to a typedef-name or decltype
specifier,(since C++11) or type template parameter, it is ignored.
References are not objects; they do not necessarily occupy storage, although the compiler may allocate storage if it is necessary to implement the desired semantics (e.g. a non-static data member of reference type usually increases the size of the class by the amount necessary to store a memory address).
Because references are not objects, there are no arrays of references, no pointers to references, and no references to references:
int& a[3]; // error
int&* p; // error
int& &r; // error
Reference collapsingIt is permitted to form references to references through type manipulations in templates or typedefs, in which case the reference collapsing rules apply: rvalue reference to rvalue reference collapses to rvalue reference, all other combinations form lvalue reference:
(This, along with special rules for template argument deduction when |
(since C++11) |
Lvalue references
Lvalue references can be used to alias an existing object (optionally with different cv-qualification):
#include <iostream>
#include <string>
int main()
{
std::string s = "Ex";
std::string& r1 = s;
const std::string& r2 = s;
r1 += "ample"; // modifies s
// r2 += "!"; // error: cannot modify through reference to const
std::cout << r2 << '\n'; // prints s, which now holds "Example"
}
They can also be used to implement pass-by-reference semantics in function calls:
#include <iostream>
#include <string>
void double_string(std::string& s)
{
s += s; // 's' is the same object as main()'s 'str'
}
int main()
{
std::string str = "Test";
double_string(str);
std::cout << str << '\n';
}
When a function's return type is lvalue reference, the function call expression becomes an lvalue expression:
#include <iostream>
#include <string>
char& char_number(std::string& s, std::size_t n)
{
return s.at(n); // string::at() returns a reference to char
}
int main()
{
std::string str = "Test";
char_number(str, 1) = 'a'; // the function call is lvalue, can be assigned to
std::cout << str << '\n';
}
Rvalue referencesRvalue references can be used to extend the lifetimes of temporary objects (note, lvalue references to const can extend the lifetimes of temporary objects too, but they are not modifiable through them):
More importantly, when a function has both rvalue reference and lvalue reference overloads, the rvalue reference overload binds to rvalues (including both prvalues and xvalues), while the lvalue reference overload binds to lvalues:
This allows move constructors, move assignment operators, and other move-aware functions (e.g. Because rvalue references can bind to xvalues, they can refer to non-temporary objects:
This makes it possible to move out of an object in scope that is no longer needed:
Forwarding referencesForwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of
auto&& except when deduced from a brace-enclosed initializer list:
See also template argument deduction and |
(since C++11) |
Dangling references
Although references, once initialized, always refer to valid objects or functions, it is possible to create a program where the lifetime of the referred-to object ends, but the reference remains accessible (dangling). Accessing such a reference is undefined behavior. A common example is a function returning a reference to an automatic variable:
std::string& f()
{
std::string s = "Example";
return s; // exits the scope of s:
// its destructor is called and its storage deallocated
}
std::string& r = f(); // dangling reference
std::cout << r; // undefined behavior: reads from a dangling reference
std::string s = f(); // undefined behavior: copy-initializes from a dangling reference
Note that rvalue references and lvalue references to const extend the lifetimes of temporary objects (see Reference initialization for rules and exceptions).
If the referred-to object was destroyed (e.g. by explicit destructor call), but the storage was not deallocated, a reference to the out-of-lifetime object may be used in limited ways, and may become valid if the object is recreated in the same storage (see Access outside of lifetime for details).
Notes
Feature-test macro | Value | Std | Feature |
---|---|---|---|
__cpp_rvalue_references |
200610L | (C++11) | Rvalue references |
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
CWG 1510 | C++11 | cv-qualified references could not be formed in the operand of decltype |
allowed |
CWG 2550 | C++98 | parameters could have type “reference to void” | now allowed |
External links
Thomas Becker, 2013 - C++ Rvalue References Explained |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/language/reference