CSE 202: Computer Science II, Winter 2018
Storage duration
Automatic and static storage duration

All objects in C++ have a storage duration which affects that object's lifetime.

Named objects (variables) have their storage duration implicitly set depending on the scope in which they are defined. Variables declared in local scope have automatic storage duration by default, thus a variable declared anywhere inside a function has automatic storage duration by default. Variables defined in namespace scope always have static storage duration, thus any variable declared outside a function has static storage duration.

Objects with automatic storage duration last until the end of the block. Objects with static storage duration last until the end of the program.

When an object reaches the end of it's lifetime, it gets destroyed. If an object is a class type object, then it's destructor gets invoked right before it gets destroyed.

The following program let's you see the order of initialization and destruction of variables t1 and t2. Since t1 is declared in namespace scope, it has static storage duration and it has a longer lifetime than t1 which has automatic storage duration.

#include <iostream> struct T { T() { std::cout << "T constructor, this = " << this << std::endl; } ~T() { std::cout << "T destructor, this = " << this << std::endl; } }; T t1; int main() { std::cout << "Press enter to continue..." << std::flush; std::cin.get(); T t2; return 0; }
Static local variables

A local variable declared with the static specifier will have static storage duration instead of the usual automatic storage duration. A static local variable's lifetime is not bound to the scope of the function like other local variables are, thus it only gets initialized once during the first call to the function and it gets destroyed during program termination.

This function uses a static local variable to keep track of the number of times it's called:

void f() { static int calls = 0; std::cout << "f() call count: " << ++calls << std::endl; }
Dynamic storage duration

An object created with a new expression has dynamic storage duration. Here are 3 ways you can create an object with a new expression:

int* a = new int; // Default initialized dynamic storage int* b = new int(); // Value initialized dynamic storage int* c = new int(4); // Direct initialized dynamic storage

Objects with dynamic storage duration last until they are manually destroyed with a delete expression. All objects created with new must be destroyed with delete, so the above example must be matched with:

delete c; delete b; delete a;

at some point before the program terminates. Arrays can also be created with new:

int* d = new int[100]; // Dynamic storage array with default-initialized elements int* e new int[100](); // Dynamic storage array with value-initialized elements // ... delete[] e; delete[] d;