logo

C++ - Storage Duration

Memory in C++ is primarily allocated either on the stack or the heap (with small exceptions for things like string literals and static variables).

Memory Allocation Deallocation Contiguous
automatic stack code block begins code block ends contiguous
dynamic heap new delete not contiguous
static static program begins program ends
thread thread begins thread ends

Notes:

  • automatic: all local objects except for static, extern or thread_local
  • static: variables live for the lifetime of the program, in a separate part of program memory colloquially referred to as "Static Memory." Only one instance exists; objects at namespace scope, or static or extern
  • thread: each thread has its own instance

A variable (that is not explicitly marked as thread_local) has static storage duration if any of the following holds:

  • It has namespace scope.
  • It is a static data member of a class.
  • It is a static variable defined in a function.