Skip to the workspace
Pebellslearn by building
Pointers and References  ›  Capstone Project

Lifetime of Objects

Lifetime of Objects 12 minObject lifetime is the period during which an initialized object exists in its storage. For a class object it normally begins after initialization and ends when destruction starts; storage can outlast the object.

cpp / Lifetime of Objects

Explore each scene at your own pace.

01 · The rule

The rule

Lifetime of Objects

Object lifetime is the period during which an initialized object exists in its storage. For a class object it normally begins after initialization and ends when destruction starts; storage can outlast the object.

Follow construction and destruction, then identify a reference that outlives its object.

When a Rocket Run level ends, the music should stop, the enemies should vanish and the save file should close, in a sensible order and without anyone remembering to call a cleanup function. C++ makes this automatic, because every object has a precise lifetime with a beginning and an end you can predict.

The rule

Objects die in reverse order of birth, at the end of their scope.

A constructor runs when an object is created, and its lifetime begins. A destructor, written ~Name(), runs when the lifetime ends. A small tracer makes the timing visible:

struct Tracer {
    std::string name;
    Tracer(std::string n) : name(n) { std::cout << "start " << name << '\n'; }
    ~Tracer() { std::cout << "end " << name << '\n'; }
};

int main() {
    Tracer level("level");
    {
        Tracer boss("boss");
    }
    Tracer music("music");
}

Rules to trace any program:

  • A local object ends at the closing brace of its scope, including on an early return.
  • Locals in the same scope end in reverse order of creation, like plates taken off a stack.
  • A temporary, such as the result of std::string("a") + "b", ends at the end of the full statement that created it.
  • A static object ends after main returns.

This is the basis of a central C++ idea: put cleanup in a destructor, and it happens on time, every time.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.