C++ References &
To declare an lvalue reference type, we use an ampersand (&
) in the type declaration:
int // a normal int type
int& // an lvalue reference to an int object
double& // an lvalue reference to a double object
For those of you already familiar with pointers, the ampersand in this context does not mean “address of”, it means “lvalue reference to”.
Lvalue reference variables
an lvalue reference variable is a variable that acts as a reference to an lvalue(usually another variable).
int main()
{
int x = 5; // x is a normal integer variable
int& ref = x ; // ref is an lvalue reference variable that can now be used as an alias for variable x
cout << x << '\n'; // print the value of x (5)
cout << ref << '\n'; // print the value of x via ref (5)
}
From the compiler's perspective, it doesn't matter whether the ampersand is “attached” to the type name (int& ref
) or the variable's name (int &ref
), and which you choose is a matter of style. Modern C++ programmers tend to prefer attaching the ampersand to the type, as it makes clearer that the reference is part of the type information, not the identifier.
When defining a reference, place the ampersand next to the type (not the reference variable’s name).
✅☑️ int& ref
,❌❎ int &ref
Favor passing by const reference int& x
over passing by non-const reference const int& x
unless you have a specific reason to do otherwise (e.g. the function needs to change the value of an argument).
Because
class types
such asstring
,vector
,deque
etc can be expensive to copy (sometimes significantly so), class types are usually passed byconst reference
if that particular variable need not be modified.