Tech News
← Back to articles

C++: zero-cost static initialization

read original related products more articles

Zero-cost statics in C++

"Усердие все превозмогает!"

К. Прутков, Мысли и афоризмы, I, 84

In C and C++ a static variable can be defined in a function scope:

int foo() { static int counter = 1; printf("foo() has been called %i times.

", counter++); ... }

Technically, this defines counter as an object of static storage duration that is allocated not within the function activation frame (which is typically on the stack, but can be on the heap for a coroutine), but as a global object. This is often used to shift computational cost out of the hot path, by precomputing some state and storing it in a static object.

When exactly a static object is initialised?

For C this question is vacuous, because the initialiser must be a compile-time constant, so the actual value of the static object is embedded in the compiled binary and is always valid.

C++ has a bizarrely complicated taxonomy of initialisations. There is static initialisation, which roughly corresponds to C initialisation, subdivided into constant-initialisation and zero-initialisation. Then there is dynamic initialisation, further divided into unordered, partially-ordered and ordered categories. None of these, however, captures our case: for block-local variables, the Standard has a special sub-section in "Declaration statement" [stmt.dcl.4]:

... continue reading