Every object has a lifetime the language defines
The objective is to be able to say, for any object in a C++ program, where it lives, when it is constructed and when it is destroyed, and to recognise the code patterns that use an object outside that window.
C++ has no garbage collector. Instead each object has a storage duration that fixes its lifetime:
| Storage duration | How you get it | Constructed | Destroyed |
|---|---|---|---|
| automatic | local variables, parameters | when the declaration is reached | at the end of the enclosing scope, in reverse order |
| static | globals, namespace-scope and static variables | globals before main; function-local static on the first call | after main returns, in reverse order of construction |
| thread | thread_local variables | per thread, on first use or thread start | when the thread exits |
| dynamic | new (or containers and smart pointers that call it) | at the new expression | only when delete runs |
Automatic objects live on the stack: allocation is just moving the stack pointer, deallocation is free, and the memory is hot in cache. The stack is small (typically 8 MB for the main thread on Linux, often less for other threads), so a local std::array<double, 10'000'000> overflows it. Dynamic objects live on the heap: any size, any lifetime, but each allocation goes through the allocator, which is far slower than a stack bump and can fragment memory. Containers such as std::vector and std::string are small objects that can sit on the stack while their elements live on the heap. (Allocation strategies are covered in QD04.)
Function-local statics are initialised exactly once, and since C++11 that initialisation is thread-safe. Globals in different translation units are initialised in an unspecified order relative to each other, so a global that uses another file's global during its own construction may see it unconstructed (the "static initialisation order fiasco"). The usual fix is a function returning a reference to a function-local static.
Watching lifetimes happen
A class that prints from its constructor and destructor makes lifetimes visible:
#include <iostream>
#include <string>
struct Tracer {
std::string name;
explicit Tracer(const std::string& n) : name(n) { std::cout << " ctor " << name << '\n'; }
~Tracer() { std::cout << " dtor " << name << '\n'; }
};
Tracer global("global"); // static storage: built before main, destroyed after it
void touch() {
static Tracer once("static-local"); // built on first call only
}
int main() {
std::cout << "main begins\n";
{
Tracer a("a");
Tracer b("b");
} // automatic storage: destroyed in reverse order, b then a
touch();
touch();
Tracer* h = new Tracer("heap"); // dynamic storage: lives until delete
delete h;
std::cout << "main ends\n";
}
ctor global
main begins
ctor a
ctor b
dtor b
dtor a
ctor static-local
ctor heap
dtor heap
main ends
dtor static-local
dtor global
Points to notice: the global is built before main prints anything; locals die in reverse order of construction; the second touch() does not rebuild the static; statics are destroyed after main in reverse order of their construction. Had we forgotten delete h, "dtor heap" would never print: the memory would leak and the destructor would never run.
Construction and destruction order within a class
For an object of a derived class, construction runs:
- base classes, in the order they are listed in the class definition;
- non-static data members, in the order they are declared in the class, regardless of the order you write them in the constructor's initialiser list;
- the constructor body.
Destruction is the exact reverse: destructor body, members in reverse declaration order, then bases in reverse order. Two consequences interviewers probe:
- If member
bis initialised from membera, thenamust be declared beforeb. Writingafirst in the initialiser list does not help. Clang and GCC warn (-Wreorder) when the list order differs from declaration order. - When the constructor body runs, every member is already fully built; when the destructor body runs, every member is still alive. That is what makes RAII (next lesson) work.
Worked example
predict the output of a derived class with misordered initialisers
What does this program print, and what does the compiler say about it?
#include <iostream>
struct Noisy {
const char* n;
explicit Noisy(const char* s) : n(s) { std::cout << "ctor " << n << '\n'; }
~Noisy() { std::cout << "dtor " << n << '\n'; }
};
struct Base {
Noisy tag{"Base::tag"};
Base() { std::cout << "Base body\n"; }
~Base() { std::cout << "~Base body\n"; }
};
struct Feed : Base {
Noisy second;
Noisy first;
Feed() : first("first"), second("second") { std::cout << "Feed body\n"; }
~Feed() { std::cout << "~Feed body\n"; }
};
int main() {
Feed f;
std::cout << "--- end of main ---\n";
}
Show solutionHide solution
Apply the rules in order.
- The base
Baseis built first. Its own members come before its body:ctor Base::tag, thenBase body. - Then
Feed's members in declaration order:secondis declared beforefirst, soctor secondthenctor first, even though the initialiser list namesfirstfirst. - Then
Feed body. - At the end of
main, everything unwinds in reverse:~Feed body,dtor first,dtor second,~Base body,dtor Base::tag.
Compiling with -Wall gives:
warning: field 'first' will be initialized after field 'second' [-Wreorder-ctor]
and running it prints:
ctor Base::tag
Base body
ctor second
ctor first
Feed body
--- end of main ---
~Feed body
dtor first
dtor second
~Base body
dtor Base::tag
The warning matters: if second had been initialised from first, it would have read an unconstructed object. Fix it by making the initialiser list match the declaration order.
new and delete pitfalls, and undefined behaviour
Every new must be matched by exactly one delete of the right form, on every path out of the code, including exceptions. Each way of getting this wrong is a classic bug:
| Mistake | Example | Result |
|---|---|---|
| leak | new with no delete, or an early return/exception before it | memory and the destructor's work (closing a socket, flushing a file) are lost |
| mismatched form | int* p = new int[8]; delete p; | undefined behaviour; arrays need delete[] |
| double delete | two owners both delete the same pointer | undefined behaviour, often heap corruption |
| use after free | read through a pointer after delete | undefined behaviour |
| delete of non-heap memory | int x; delete &x; | undefined behaviour |
Undefined behaviour (UB) means the standard places no requirement on the program at all. It is not "returns garbage": the optimiser assumes UB never happens and may delete checks or reorder code on that basis, so a UB bug can surface far from its cause, or only at -O2. Other common UB: signed integer overflow, reading an uninitialised local, out-of-bounds indexing, and returning a reference to a local:
int* prices = new int[4]{100, 101, 102, 103};
delete[] prices;
std::cout << prices[0] << '\n'; // use after free: UB, any output (or none) is "correct"
Tools catch what reading misses: compile tests with -fsanitize=address,undefined (AddressSanitizer reports use-after-free, double free and out-of-bounds access with a stack trace) and turn on -Wall -Wextra. The real fix is structural: in modern C++ application code you should almost never write delete. Let containers, RAII classes and smart pointers own heap memory (next lesson, and QD04).
Returning a local by value is fine and cheap: std::string make_label() { std::string s = "ESZ6"; return s; } either constructs the result directly in the caller's storage (copy elision) or moves it. Only returning a reference or pointer to a local dangles.
Knowledge check
struct C { A a; B b; C() { print("C"); } ~C() { print("~C"); } }; where A and B print their own name in constructors and ~A, ~B in destructors. What does { C c; } print?
Knowledge check
int* p = new int[8]; ... delete p; What is the status of this code?
Knowledge check
Which function is well defined?
Key takeaways
- Storage duration decides lifetime: automatic (scope), static (whole program), thread, and dynamic (until
delete). - Locals and statics are destroyed in reverse order of construction. Members are built in declaration order, bases first, and destroyed in reverse.
- The stack is fast but small; the heap is flexible but each allocation costs. Containers keep their elements on the heap.
- Mismatched
new[]/delete, double delete, use after free and returning a reference to a local are undefined behaviour, which the optimiser may exploit. Use sanitizers to find them. - Avoid raw
new/deletein application code; let owning objects manage memory.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).