Skip to content
LeetQuant
QD03 C++ Fundamentals

QD03 · C++ Fundamentals · Lesson 2 of 6

Memory and Object Lifetime

Stack versus heap, the four storage durations, the exact order of construction and destruction, and the new/delete mistakes that produce undefined behaviour.

17 min

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 durationHow you get itConstructedDestroyed
automaticlocal variables, parameterswhen the declaration is reachedat the end of the enclosing scope, in reverse order
staticglobals, namespace-scope and static variablesglobals before main; function-local static on the first callafter main returns, in reverse order of construction
threadthread_local variablesper thread, on first use or thread startwhen the thread exits
dynamicnew (or containers and smart pointers that call it)at the new expressiononly 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:

  1. base classes, in the order they are listed in the class definition;
  2. 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;
  3. 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 b is initialised from member a, then a must be declared before b. Writing a first 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 solution

Apply the rules in order.

  1. The base Base is built first. Its own members come before its body: ctor Base::tag, then Base body.
  2. Then Feed's members in declaration order: second is declared before first, so ctor second then ctor first, even though the initialiser list names first first.
  3. Then Feed body.
  4. 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:

MistakeExampleResult
leaknew with no delete, or an early return/exception before itmemory and the destructor's work (closing a socket, flushing a file) are lost
mismatched formint* p = new int[8]; delete p;undefined behaviour; arrays need delete[]
double deletetwo owners both delete the same pointerundefined behaviour, often heap corruption
use after freeread through a pointer after deleteundefined behaviour
delete of non-heap memoryint 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/delete in application code; let owning objects manage memory.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).