Object Lifetime
When objects are created and destroyed.
When Objects Are Born
An object's lifetime begins after its storage is allocated and its constructor finishes. From that point it is fully usable.
#include <iostream>
struct Widget {
Widget() { std::cout << "born\n"; }
};
int main() {
Widget w; // constructor runs here
}When Objects Die
Lifetime ends when the destructor runs. For a stack object that happens at the closing brace of its scope.
#include <iostream>
struct Widget {
~Widget() { std::cout << "dies\n"; }
};
int main() {
Widget w;
std::cout << "alive\n";
} // ~Widget runs here