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
staticobject ends aftermainreturns.
This is the basis of a central C++ idea: put cleanup in a destructor, and it happens on time, every time.