skip to content

In C++, what are the four storage durations, and when does an object of each one stop existing?

level: juniorimportance: must knowfreq 62%

answer

  1. four categories, not stack and heap
  2. the closing brace of the block
  3. whole program versus one thread
  4. dynamic ends only on delete

basics

~20 s

C++ has automatic, static, thread and dynamic storage duration. Automatic objects die when their block exits, static objects during program exit, thread_local objects when their thread ends, and dynamic objects only when the program destroys them, usually with delete.

solid answer

~40 s

The construct that creates an object fixes its storage duration. A block-scope variable not declared `static`, `thread_local` or `extern` has **automatic** duration and is destroyed when its block exits, in reverse order of construction. Namespace-scope variables, class `static` data members and block variables declared `static` have **static** duration: the storage lasts for the whole program, and constructed objects are destroyed during `std::exit`, which returning from `main` invokes, in reverse order of construction. A `thread_local` variable has **thread** duration: there is one object per thread, destroyed when that thread finishes. An object created by a `new`-expression has **dynamic** duration and lives until the program ends it with `delete`, whichever scope created it. Members take the duration of the object that contains them.

code

cpp · 21 lines
cpp
#include <cstdio>
struct Tracer {
  const char* name;
  explicit Tracer(const char* n) : name(n) { std::printf("construct %s\n", name); }
  ~Tracer() { std::printf("destroy   %s\n", name); }
};
Tracer global{"global (static)"};
thread_local Tracer per_thread{"per_thread (thread)"};
void touch() {
  static Tracer counter{"counter (static, block scope)"};
  Tracer local{"local (automatic)"};
}
int main() {
  std::puts("main starts");
  touch();
  touch();
  Tracer* heap = new Tracer{"heap (dynamic)"};
  (void)per_thread.name;  // first use in this thread
  delete heap;
  std::puts("main returns");
}

go deeper

for a junior

Recall the four names and the end point of each: block exit, program exit, thread exit, explicit delete. Say that a static local keeps its value between calls.

for a middle

Explain that statics are destroyed in reverse order of construction during std::exit, that block-scope statics are built on first pass, and that members inherit their complete object's duration.

for a senior

Show you separate storage duration from object lifetime, and connect the static duration of globals to the startup and shutdown ordering problems they cause in multi-file programs.

for a principal

Frame storage duration as a design input: which state may be global, which must be per thread, and who owns every dynamic object, so the team never debugs exit-time crashes.

## Four durations, four end points The **storage duration** of an object is the property that sets the minimum potential lifetime of the storage that holds it. The standard does not let you choose it separately: it follows from the construct that created the object, and there are exactly four. | Storage duration | How an object gets it | When the storage ends | |---|---|---| | **automatic** | a block-scope variable not declared `static`, `thread_local` or `extern`; a function parameter | when the block that declares it exits | | **static** | a namespace-scope variable, a class `static` data member, a block variable declared `static` | at the end of the program | | **thread** | any variable declared `thread_local` | when the thread it belongs to ends | | **dynamic** | an object created by a `new`-expression, or implicitly created in allocated storage | when the program releases it, usually with `delete` | Subobjects and reference members take the duration of their **complete object**: a `std::string` member of a global has static duration, the same member of a local has automatic duration. "Stack" and "heap" are how implementations usually place automatic and dynamic objects; the language itself speaks only of durations. ## Watching the order The tracer program in the code example prints one line from every constructor and destructor. Read top to bottom, its output shows each rule: 1. The namespace-scope `global` is constructed before `main` starts. The standard lets an implementation defer that initialization, but this build ran it first. 2. The block-scope `static counter` is constructed the first time control passes its declaration and never again: the second call to `touch()` skips it. 3. `local` is constructed and destroyed on **every** call, because its block exits every time. 4. The `new`-ed object lives until the explicit `delete`, regardless of which scope created it. 5. When `main` returns, `std::exit` runs: the main thread's `thread_local` object is destroyed first, then the static objects in reverse order of construction, `counter` before `global`. ## Lifetime is not the same thing Storage duration describes the **storage**. An object's **lifetime** runs from the end of its initialization to the start of its destruction, and it can be shorter than the storage. A block-scope `static` has storage for the whole program, but its object does not exist until control first reaches the declaration. Likewise a `thread_local` at namespace scope may be initialized only when its thread first uses a thread-duration variable from the same translation unit; whether that happens before the thread's first statement or later is implementation-defined. Keeping the two words apart is what lets you reason about a variable whose storage exists but whose object has not been built yet, or has already been destroyed. ## Mistakes that come up in interviews - Treating "local" and "automatic" as synonyms: a `static` local is local in **scope** but static in **duration**. - Assuming a local lives until the function returns: it dies at the end of its innermost block, so a pointer to it taken inside an `if` dangles after that closing brace. - Assuming a `new`-ed object is cleaned up when the pointer holding it goes out of scope: the pointer is automatic, the object is dynamic, and only `delete` (or an owner such as `std::unique_ptr`) ends it. - Assuming globals are never destroyed: constructed static objects are destroyed during `std::exit`. Only paths that skip it, such as `std::quick_exit` or `std::abort`, leave them alive. - Reading `static` as one meaning: at namespace scope it gives a variable internal linkage (its duration is static either way), in a block it changes the duration, and in a class it makes one member shared by every instance. ## How to answer Name all four durations with the construct that produces each, give each one's end point, and add one nuance: block-scope statics are built on first use, statics are destroyed in reverse order of construction during `std::exit`, and thread duration means one object per thread. Static initialization order across files and the thread-safety of function-local statics are the natural next questions.

  • Does the static keyword mean the same thing at namespace scope and inside a function?
    No. A namespace-scope variable already has static storage duration, so `static` there only gives it internal linkage, hiding it from other translation units. Inside a block, `static` changes the duration from automatic to static while the name stays visible only in that block. On a class data member, `static` makes one object shared by every instance, again with static duration.
  • What storage duration does a member of a class object have?
    The duration of its complete object. A member subobject of a local variable has automatic duration, of a global has static duration, and of an object created with `new` has dynamic duration. The member's own declaration never picks a duration; `static` on a member makes it a separate, class-wide object instead of a subobject.

  • A local variable lives until the function returns, not until its block ends.
  • An object made with new is destroyed when the pointer holding it goes out of scope.
  • Global objects are never destroyed; the operating system just reclaims their memory.
  • A thread_local variable is one object that all threads share.
  • A static local variable is visible to other functions in the same file.