← Runtimes
Runtimes

C++ object lifetime: copies, moves and the rule of five

Deterministic destruction, and the special members that keep one owner per resource.

Choose copy, move, and assignment behavior that preserves a resource owner’s lifetime guarantees.

Outcome

Decide which special members a resource-owning class needs, give each copy its own resource, make moves noexcept so containers use them, and write an assignment that leaves the object valid when the copy fails.

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.

RAII
Resource acquisition is initialization: a constructor acquires a resource and the destructor releases it when the object’s lifetime ends.
Rule of three / five
A class that defines a destructor, copy constructor or copy assignment usually needs all three; with moves, all five.
Rule of zero
Hold resources in members that manage themselves, so the class needs none of the five.
Moved-from object
The source of a move: valid but unspecified for library types; for your own owners, typically owning nothing.
Strong exception guarantee
An operation either succeeds or leaves its protected value unchanged. In this lab that value includes the target upload’s name and owned slot contents.

Object lifetime and resource ownership

An object’s lifetime runs from its construction to its destruction. RAII ties a resource such as an allocated array or open file to that lifetime: acquiring it establishes an owner, and normal destruction releases it. The object’s storage and the resource it owns can have different lifetimes.

Copy construction creates another object from an existing one; assignment changes an object that already exists. A move can transfer ownership instead of duplicating the resource. The rule of five asks these operations and the destructor to express one coherent ownership policy. Self-managing members can supply that policy through their own operations: the rule of zero.

01Copies

What does the implicit copy of an owner copy?

The upload queue must retain a failed file for retry while continuing to accept new files. Its Upload class exclusively owns one storage slot, but an implicit copy gives two objects the same slot number. First establish independent retry ownership, then transfer ownership during growth without duplicating large files. A replacement adds another requirement: failure must leave the previous queued file intact.

Buffer allocates an array in its constructor and deletes it in its destructor. It declares no copy constructor, so the compiler generates one that copies each member, including the pointer.

This reduced filename owner isolates pointer copying from the upload queue’s storage policy. Its inner-scope copy frees the array before the original is read. The recorded undefined-behavior outcome diagnoses ownership; it is not a portable test to reproduce.

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

/// Owns a heap copy of a file name.

struct Buffer {
    char *data;
    explicit Buffer(const char *text) : data(new char[std::strlen(text) + 1]) {
        std::strcpy(data, text);
    }

    ~Buffer() {
        delete[] data;
    }
};

int main() {
    Buffer original("photo.jpg");
    {
        Buffer copy = original; // the implicit copy copies the pointer
        std::printf("copy: %s\n", copy.data);
        std::fflush(stdout);
    } // copy's destructor deletes the array
    std::printf("original after the copy is gone: %s\n", original.data);
    std::fflush(stdout);
} // original's destructor deletes it again
Buffer declares a destructor but no copy constructor. On the lab runner (GCC 12.2, glibc), what happened after the copy went out of scope?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
g++ -std=c++23 -Wall -Wextra main.cpp -o main && ./main

The quoted outputs are historical observations from GCC 12.2/libstdc++ with glibc, not new runs. shallow.cpp deliberately has undefined behavior: its garbage bytes/abort are one observation, not a portable test expectation. The lab instead uses authored integer storage slots with explicit guard failures; it does not perform real uploads or manage native file descriptors.

02Moves

When does a vector move its elements?

Once retry copies are independent, inspect growth: a full vector needs new storage for its elements. A resource handover can avoid storage::copy, but a throwing move could have changed earlier source elements before failure. The recorded implementation uses a copy path for the potentially throwing mover and a transfer path for the noexcept mover.

The reduced types below omit upload storage and count their copy/move constructor calls during growth to 100 elements. Only one move constructor is marked noexcept; the experiment isolates the library’s transfer choice, not upload throughput.

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

int copies = 0, moves = 0;

struct MaybeThrows {
    int id;
    explicit MaybeThrows(int id) : id(id) {}
    MaybeThrows(const MaybeThrows &other) : id(other.id) {
        ++copies;
    }
    MaybeThrows(MaybeThrows &&other) : id(other.id) {
        ++moves;
    }
};

struct NeverThrows {
    int id;
    explicit NeverThrows(int id) : id(id) {}
    NeverThrows(const NeverThrows &other) : id(other.id) {
        ++copies;
    }
    NeverThrows(NeverThrows &&other) noexcept : id(other.id) {
        ++moves;
    }
};

template <typename T>

void grow(const char *name) {
    copies = moves = 0;
    std::vector<T> items;

    for (int i = 0; i < 100; ++i)
        items.emplace_back(i);
    std::printf("%s: %d copies, %d moves\n", name, copies, moves);
}

int main() {
    grow<MaybeThrows>("move constructor without noexcept");
    grow<NeverThrows>("move constructor with noexcept");
}
Both types have copy and move constructors. What did the recorded GCC 12.2/libstdc++ build do while each vector grew to 100 elements?

03Assignment

What if the copy fails halfway through an assignment?

Assignment replaces a resource the object already owns. A natural first version releases the old resource and then copies the new one. If the copy throws, the object has already released what it owned but still refers to it.

The same order also breaks a = a: the object releases the very resource it is about to copy.

Two ways to write copy assignment for an owner
OrderIf the copy throwsa = a
Release, then copyThe object names a released resourceCopies a resource it just released
Copy, then release (or copy-and-swap)The object keeps its old valueMakes a copy, then releases the old one
An assignment operator closes its own slot first, then copies the source slot. The copy throws. What does the object hold afterwards?

04Practice

Fix the upload queue

The lab is an upload queue with authored integer storage slots. Easy first establishes independent ownership using copyable files of 0–1000 bytes. Medium admits larger files: growth must transfer their existing slots, while an explicit retry over 1000 bytes is rejected. Hard adds replacement and rejection safety. Closing/reading an invalid slot triggers an explicit guard failure; the report counts storage::copy calls, not native allocation or all C++ copy operations.

The upload queue

Give each copy its own slot, move uploads as the queue grows, then make replace safe when a copy fails.

  1. easy · R-LIFETIME-V4-1 Copy the slot, not the number
  2. medium · R-LIFETIME-V4-2 Move instead of copying
  3. hard · R-LIFETIME-V4-3 Assign without losing the upload
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.