IT lexicon › Programming › Guard variable

Guard variable

Programming På svenska → Updated: 2026-11-07

The hidden flag that tracks whether a function-local static in C++ has been initialised yet, and makes sure that happens exactly once even with several threads around.

C++11 promised that function-local statics are initialised thread-safely, a feature often called magic statics. The Itanium ABI implements it with a 64-bit guard object next to the variable, mangled with the prefix _ZGV. The fast path is a single acquire load and a branch. If the first byte is zero, the code calls __cxa_guard_acquire, runs the constructor, and __cxa_guard_release marks it done. If the constructor throws, __cxa_guard_abort drops the lock so the next call tries again.

MSVC only delivered the same guarantee in Visual Studio 2015. Anyone who knows the code is single-threaded can switch the machinery off with -fno-threadsafe-statics, which embedded code on a tight size budget sometimes does.

← Back to the lexicon