A reference is a second name for an object that already exists. Once it is bound, it cannot be bound to anything else, and it can never be empty. Those two rules are what make a reference safer than a pointer for most of the work that you do.
The previous lesson in this module covered "How Do Pointer Arithmetic and Arrays Interact?", and the next lesson in this module is about "What Causes Dangling Pointers and How Do You Avoid Them?".
A reference is a second name
After the declaration, the two names are the same object.
#include <iostream>
int main() {
int duration = 180;
int& alias = duration;
std::cout << "duration: " << duration << '\n';
std::cout << "alias: " << alias << '\n';
alias = 240;
std::cout << "after write through alias: " << duration << '\n';
duration = 300;
std::cout << "after write through original: " << alias << '\n';
return 0;
}The output shows that the two names track each other perfectly.
duration: 180
alias: 180
after write through alias: 240
after write through original: 300References cannot be reseated
Attempting to change what a reference refers to does not compile.
#include <iostream>
void assign_through_reference(int& target) {
target = 999;
}
int main() {
int first = 1;
int second = 2;
int& alias = first;
std::cout << "alias sees: " << alias << '\n';
std::cout << "second is: " << second << '\n';
// alias = second; // does not compile: a reference cannot be reseated
assign_through_reference(alias);
std::cout << "after function: " << first << '\n';
return 0;
}The output shows that writing through the alias reached the original object.
alias sees: 1
second is: 2
after function: 999References cannot be null
There is no such thing as a null reference.
#include <iostream>
int main() {
int value = 42;
int& alias = value;
// int& missing; // does not compile: no default construction
std::cout << "value: " << value << '\n';
std::cout << "alias: " << alias << '\n';
return 0;
}The output confirms that the alias is usable from the moment that it is declared.
value: 42
alias: 42References in function parameters
A const reference parameter is how a function reads a large object without copying it.
#include <iostream>
#include <string>
struct Track {
std::string title;
int seconds;
};
void describe(const Track& track) {
std::cout << track.title << " runs " << track.seconds << " seconds\n";
}
void set_duration(Track& track, int seconds) {
track.seconds = seconds;
}
int main() {
Track track = {"Slow Tide", 243};
describe(track);
set_duration(track, 300);
describe(track);
return 0;
}The output shows the read-only call and then the modifying call.
Slow Tide runs 243 seconds
Slow Tide runs 300 secondsReferences in range-based for loops
The range-based for loop can bind each element either by value or by reference, and the choice decides whether you can modify the original collection.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> tracks = {"one", "two", "three"};
for (std::string& track : tracks) {
track += " (edited)";
}
for (const std::string& track : tracks) {
std::cout << track << '\n';
}
return 0;
}The output shows the edits landed in the original vector.
one (edited)
two (edited)
three (edited)Choosing between a reference and a pointer
Use a reference when the object is always there. Use a pointer when it might not be, and when you need to reseat it or to pass a pointer to a pointer.
the situation use
--------------------------------- ------------------------------------
the object is always present a reference
the object might not be there a pointer, or std::optional
the function may reseat it a pointer to a pointer
the object is large a const reference
the function needs to change it a plain reference
References as return values
The rule is the same as for parameters. The referenced object has to outlive the call.
#include <iostream>
#include <string>
struct Playlist {
std::string name;
int tracks;
};
const std::string& longest_name(const Playlist& playlist) {
static const std::string empty = "";
if (playlist.name.empty()) {
return empty;
}
return playlist.name;
}
int main() {
Playlist playlist = {"Late Night Sessions", 42};
std::cout << "name: " << longest_name(playlist) << '\n';
return 0;
}The output shows the reference being used directly without a copy.
name: Late Night SessionsQuick reference
- A reference is a second name for an existing object, and it can never be reseated.
- A reference can never be null, so a function that takes one can always use it.
- Use a const reference for a parameter that is only read, and a plain reference when it is changed.
- In a range-based for loop, a reference lets you modify the original collection.
- A pointer is needed when the object might be missing, or when the binding has to change.
- A reference that is returned has to point at something that outlives the call.
Try it yourself: write a function that takes a const reference to a string and prints it in upper case without copying it, and then one that takes a plain reference and appends a suffix to it. Call both on the same string and check that the first one leaves it alone while the second one changes it. Finally, write a function that returns a reference to the longer of two strings and call it on a pair where the second one is longer.