← Back to course: Modern C++ from scratch

References and const

Video coming soon

In the previous lesson we saw that parameters are copied. For many tasks that is not what you want: either you need the function to modify the original variable, or the object is large and copying it is wasteful. C++ solves both cases with references. A reference is an alias: another name for a variable that already exists. Together with const, they form the most important tool for writing efficient and safe functions.

What a reference is

It is declared with & after the type: int& r = x; makes r another name for x. Everything you do with r you do with x. A reference must be initialized when declared and can never be reassigned to refer to another variable; from birth to death, it designates the same object. There is no empty reference, which removes a whole class of errors that pointers do have. It is important to tell it apart from a copy: int y = x; creates a new, independent variable.

cpp
#include <iostream>

int main() {
    int x{10};
    int& r = x;    // r is an alias of x
    int y = x;     // y is an independent copy

    r = 20;        // changes x
    y = 99;        // does not change x

    std::cout << "x = " << x << ", r = " << r << ", y = " << y << '\n';
    return 0;
}

Pass by reference and by const reference

If the parameter is int& the argument is not copied, and the function can change it: this is how you return several results or modify data in place. If the parameter is const std::string& there is no copy either, but the function promises not to modify the object, and the compiler enforces it. This is the practical rule you will follow almost always: small types (int, double, char, bool) by value; large types (string, vector, classes) by const reference if they are only read, and by non-const reference if they must change.

cpp
#include <iostream>
#include <string>

void swapValues(int& a, int& b) {
    int tmp = a;
    a = b;
    b = tmp;
}

void addExclamation(std::string& text) {
    text += "!";                 // modifies the caller's string
}

std::size_t countLetters(const std::string& text) {
    // text += "x";             // error: text is const
    return text.size();         // read only, no copy
}

bool minMax(int a, int b, int& smallest, int& largest) {
    smallest = (a < b) ? a : b;
    largest = (a < b) ? b : a;
    return a != b;
}

int main() {
    int p{1};
    int q{2};
    swapValues(p, q);
    std::cout << p << ' ' << q << '\n';   // 2 1

    std::string word{"Hey"};
    addExclamation(word);
    std::cout << word << " has " << countLetters(word) << " letters\n";

    int lo{};
    int hi{};
    minMax(8, 3, lo, hi);
    std::cout << lo << ' ' << hi << '\n';  // 3 8
    return 0;
}

const everywhere

A const reference can bind to almost any value, even a literal or a temporary result: countLetters("hello") works because a temporary std::string is created and lives during the call. A non-const reference does not allow that: addExclamation("hello") does not compile. Two classic mistakes: returning a reference to a local variable (the variable dies when the function ends and the reference dangles, undefined behavior) and forgetting const on parameters that are not modified, which prevents passing literals and temporaries. Marking const everything that does not change also helps the reader understand the code.

A useful nuance: a const reference can bind to a temporary value, such as a function result or a literal. That is why a function void print(const std::string& s) accepts print("hello") without problems, while a non-const reference (std::string&) rejects it.

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →