typestar

References & const in C++

A reference is a second name for the same object; const & is C++'s read-only borrow.

#include <string>

void shout(std::string &word) {
    word += "!";
}

std::size_t measure(const std::string &word) {
    return word.size();
}

std::size_t demonstrate() {
    std::string greeting = "hello";
    std::string &alias = greeting;    // same object, second name
    shout(alias);
    return measure(greeting);
}

How it works

  1. shout takes std::string &, so appending "!" changes the caller's string in place.
  2. measure takes const std::string &: no copy is made and no edit is allowed.
  3. std::string &alias = greeting binds a new name; mutating through it mutates greeting.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
300
Tokens
85
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 2 of 3 in Values & references, step 2 of 27 in Language basics.

← Previous Next →