← Fundamentals
Fundamentals

C++ references, auto, and copies

When does a C++ name refer to an existing object, and when does auto quietly make a copy?

Trace whether a C++ declaration creates an independent value or an alias.

Outcome

Predict whether a declaration copies or refers, explain why assigning to a reference changes its object instead of rebinding it, choose the right range-for and return types, and repair code that changes a copy.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Reference
The lvalue references T& and auto& shown here bind to an existing object once; assignment through them writes that object.
auto
In the plain value declarations shown here, deduces a type without preserving the initializer expression’s reference or top-level const.
Range-for
for (declaration : range), which initializes the declared variable from each element in turn.
Deduced return type
The shown omitted lambda return type uses plain auto deduction; decltype(auto) follows different rules.
Temporary
A temporary result such as the returned int value shown here; a non-const lvalue reference T& cannot bind to it.

Values and access to existing objects

An lvalue reference provides another name for an existing object. A separate value has its own state. Type deduction does not settle this choice by itself: plain auto and auto& request different declaration forms, and a function’s return type also affects what its caller can receive.

Follow both ends of an update: how a value or reference leaves a function or container, and how the receiving declaration retains it. A range-for makes that receiving declaration for each element. The object reached by an assignment matters as much as the number being assigned.

01auto and auto&

auto makes a new object; auto& names an existing one

A hardware-store stock report must subtract sales from stored shelves, keep separate counts as staff advance between bins, and add deliveries to existing or newly created shelves. The code can compute the right number while changing an independent value. Follow which stored object each update reaches.

Before trusting a stock adjustment, compare a local working count with an alias to a stored count. first uses auto, second uses auto&, and both increase by 10. Which changes reach the crates vector that the report prints?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <vector>

int main() {
    std::vector<int> crates{4, 6};

    auto first = crates[0];
    first += 10;

    auto &second = crates[1];
    second += 10;

    std::cout << crates[0] << ' ' << crates[1] << ' ' << first << '\n';
}
What is printed?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
clang++ -std=c++2c -Wall -Wextra -pedantic main.cpp -o main && ./main

Use the C++ setup from the first reading. This C++-only lesson follows ordinary int and Shelf values in std::vector, lvalue references written T& or auto&, and the plain auto return deduction shown in its lambdas.

02Binding once

A reference is bound once; assigning to it changes the object

The bin-entry code tries to move its current selection by assigning through a reference. In this reduced case, current starts bound to left, receives right, and right then changes separately. Predict the values before using that assignment as navigation.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>

int main() {
    int left = 1;
    int right = 7;

    int &current = left;
    current = right;
    right = 3;

    std::cout << left << ' ' << right << ' ' << current << '\n';
}
What is printed?
Loading Assignment follows the existing binding…

03Range-for

The shown range-for declarations choose a copy or an alias

The sales loop must change stored Shelf counts. This reduced test uses two distinct passes over an int vector: multiply by 10, then add 1. Which pass reaches the stored counts that the report reads?

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <iostream>
#include <vector>

int main() {
    std::vector<int> counts{1, 2, 3};

    for (auto count : counts) {
        count *= 10;
    }

    for (auto &count : counts) {
        count += 1;
    }

    std::cout << counts[0] << ' ' << counts[1] << ' ' << counts[2] << '\n';
}
What is printed?

04Deduced returns

Plain auto return deduction does not preserve the element reference

A delivery lookup returns an element for its caller to update. This reduced pair of lambdas separates the return type from the caller’s declaration: byValue has a plain deduced return, byReference says -> int&, and the caller also makes a local copy. Predict the three numbers.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#include <cstddef>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> counts{1, 2};

    auto byValue = [&](std::size_t i) { return counts[i]; };
    auto byReference = [&](std::size_t i) -> int & { return counts[i]; };

    byReference(1) += 10;

    auto copy = byReference(0);
    copy += 100;

    std::cout << byValue(0) << ' ' << counts[1] << ' ' << copy << '\n';
}
What is printed?

05Repair the hardware store

Sales, bins, then restocking

Make the stored report agree with sales, bin entries and deliveries. Bin navigation and a working count are separate state choices. Restocking must connect each returned shelf to the store’s collection, including shelves first encountered in the delivery list.

This lab is C++-only. Each file contains its includes, reader and complete caller.

Repair the hardware store

Stored sales, complete bin counts and deliveries in the store’s collection.

  1. easy · F-REFS-V4-1 Record the sales
  2. medium · F-REFS-V4-2 Fill the bins in order
  3. hard · F-REFS-V4-3 Restock every shelf
Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.