Lifetime of Objects
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
staticobject ends aftermainreturns.
This is the basis of a central C++ idea: put cleanup in a destructor, and it happens on time, every time.
The shortcut
Push on construction, pop at the brace. Keep a mental stack: each constructor pushes a name, each closing brace pops the names created inside it, newest first.
level
Push level. Output: start level.
The trap is handing out a reference or pointer to an object that is about to die. Returning std::string& to a local string compiles (with a warning), but the caller receives a name for something already destroyed. Return by value instead; modern compilers make that cheap.
Drills
Answer fast — trust the rule.
In { Tracer a("a"); Tracer b("b"); }, what are the last two lines printed?
When does a local object's destructor run?
Which function safely gives the caller a newly built player name?
When is a function's static local object destroyed?
Remember
- Objects die in reverse order of birth, at the end of their scope.
- Shortcut: push on construction, pop at the brace, newest first.
- Trap: never return a reference or pointer to a local; return by value.
