Step 2 of 8
Order of destruction
When several objects live in the same scope, the order in which they're destroyed follows a simple rule: reverse order of construction. The last object created is the first destroyed, like a stack of plates.
#include <iostream>
#include <string>
struct Step {
std::string name;
explicit Step(std::string n) : name(n) { std::cout << "open " << name << "\n"; }
~Step() { std::cout << "close " << name << "\n"; }
};
int main() {
Step outer("database");
{
Step inner("transaction");
std::cout << " doing work\n";
}
Step last("log");
std::cout << "end of main\n";
}
open database
open transaction
doing work
close transaction
open log
end of main
close log
close database
Why reverse order?
Later objects often depend on earlier ones: a transaction uses a database connection, so the transaction must be closed before the connection. Destroying in reverse order makes that correct automatically.
Blocks control lifetime
A { } block ends the lifetime of everything declared inside it. The inner block above closes the transaction before log is even created. Adding a block is the standard way to end an object's life early, for example to release a lock as soon as the critical work is done.
Members of a class are destroyed in reverse order of their declaration, after the class's own destructor body runs, following the same logic.
Your turn: without changing the struct, reorder and group the lines in main so the output is exactly:
+ A
+ B
- B
+ C
- C
- A