Skip to main content

Section 10.1 References

In the string chapter we mentioned that the a function that takes a string parameter probably should be written as:
void foo(const string& s);
Instead of:
void foo(string s);
So why is the first version preferable? To answer that question, we will start by reviewing how normal variables work. Each regular variable is a name for a different location in memory (a different box to store things in). Given this code:
int a = 5;
int b = a;
There are two storage locations, each with its own name. The second line of main make a new storage area with the name b and copies the value a has to it. When reading that code, you should picture a memory diagram that looks like this:
Figure 10.1.1. Memory diagram of a and b that each hold 5.
Changing the value in the storage named by b does not change the value stored in a. This is how things usually work in C++.
A reference changes this. A reference does not name its own storage, instead a reference always β€œpoints” to some other storage. We declare a variable to be a reference by adding & to the data type, like int& b;. The & change the type of `b β€”it no longer is an β€œint”, it is a β€œreference to an int”.

Insight 10.1.1.

When trying to pronounce complex looking data types in C++ it sometimes helps to read the backwards. int& b; can be read as β€œb is a reference to an integer”.
A memory diagram for int& b = a; should look like:
Figure 10.1.2. Memory diagram of a that holds 5 and b that is a reference to a.
b is an alias for a - it is another way to name the exact same storage that a names. If we change b, we change that value. Run this Codelens sample to see its animation of the situation:
Listing 10.1.3.
You can change either a or b and both variables β€œsee” the new value.

Note 10.1.2.

The formal name in C++ for variables that name their own storage is an lvalue (location). A reference is an rvalue (reference). It is also possible to have an rvalue reference using the symbol &&.
Those terms and the concept of an rvalue reference are beyond the scope of this book.
You have attempted of activities on this page.