In a large C++ codebase, what rule would you set for global and static objects with non-trivial constructors or destructors, and how would you enforce it?
answer
- constant initialization is free
- lazy on first use for the rest
- decide whether statics are destroyed
- make the compiler list them
basics
~20 sA common rule: globals must be constant-initialized (constexpr or constinit); anything needing runtime construction lives behind a function-local static; objects used at shutdown are never destroyed or are torn down explicitly from main. Enforce it with Clang's -Wglobal-constructors and -Wexit-time-destructors.
solid answer
~50 sThere is no single right rule, but a defensible one has three parts. First, any namespace-scope or class-static object must be **constant-initialized**: `constexpr` for constants, C++20 `constinit` for mutable state, which removes startup order entirely. Second, anything that needs runtime construction (maps, strings built from config, loggers) goes behind a **function-local static** accessor, so it is built on first use, thread-safely, in whatever order callers need. Third, decide the exit story: either such objects are **never destroyed** (heap-allocated once, or `[[clang::no_destroy]]` on Clang) so no destructor can run against a dead dependency, or shutdown happens **explicitly** from `main`. Enforcement: Clang's `-Wglobal-constructors` and `-Wexit-time-destructors` as errors on new code with a baseline for old code, since GCC 16.2 has neither warning. The trade-off to state is hidden first-call latency and intentional leaks versus startup and shutdown crashes nobody can reproduce.
code
cpp · 6 lines#include <string>
int load() { return 8; }
int g_limit = load(); // needs code at startup
std::string g_name = std::to_string(42); // needs a destructor at exit
constinit int g_max_plugins = 64; // static initialization only: no warning
int main() {}go deeper
Know that globals with constructors and destructors are risky because their construction and destruction order across files is not fully defined.
Explain constinit versus constexpr for globals and why function-local statics fix startup order but not exit order.
Show how you would find every global with dynamic initialization or an exit-time destructor in a codebase and fix the ones with cross-file dependencies.
Choose a default policy, weigh lazy construction latency and intentional leaks against irreproducible startup and shutdown crashes, and roll the rule out with tooling, a baseline and documented exceptions.
## Why a rule is needed at all Every object with static storage duration takes part in two orders the standard only partly defines. At startup, dynamic initialization across translation units is indeterminately ordered, so one global using another is a latent crash that depends on link order. At exit, static objects are destroyed in reverse order of construction, so a destructor that reaches another static can run after it is gone. In a codebase with hundreds of translation units and several teams, nobody can keep these orders in their head. The rule exists to make the dangerous cases rare, visible and reviewed. ## The options a lead weighs | Policy | Startup risk | Exit risk | Cost | |---|---|---|---| | allow any global | high: order depends on link order | high: destructors reach dead objects | none until it crashes | | only constant-initialized globals (`constexpr`, `constinit`) | none: static initialization precedes all dynamic initialization | low if destruction is trivial | some state cannot be built at compile time | | runtime objects behind function-local statics | none: built on first use | still present: lazily built objects die early | a guard check per call, first-call latency | | runtime objects never destroyed | none with lazy construction | none: no exit-time destructor | destructor side effects never run | | explicit init and shutdown from `main` | none | none | ordering maintained by hand, boilerplate | Most mature codebases combine rows rather than picking one. ## A rule that holds up 1. **Constant data and plain counters:** `constexpr` or `constinit` at namespace scope. `constinit` (C++20) makes the program ill-formed if the variable would need dynamic initialization, so a later edit cannot silently reintroduce the problem. Prefer types with trivial destruction here, such as `std::string_view` and `std::array` of literals rather than `std::string`. 2. **Runtime-built shared objects:** a function returning a reference to a function-local static. Initialization is once and thread-safe since C++11, and the order follows the call graph rather than the link line. 3. **Objects used during shutdown:** pick one exit policy per object and write it down. Either never destroy it, through `static auto* p = new Registry();` returning `*p` or Clang's `[[clang::no_destroy]]`, or give it an explicit `shutdown()` that `main` calls before returning. 4. **Resources that must close cleanly** (files that must flush, network sessions, hardware handles): never in an object destroyed implicitly at exit. Close them explicitly where the order is visible in code. 5. **Exceptions:** a namespace-scope initializer that throws calls `std::terminate`, so risky setup belongs in a function the program can handle, not in a global's constructor. ## Enforcing it - Clang's `-Wglobal-constructors` warns with "declaration requires a global constructor" or "a global destructor", and `-Wexit-time-destructors` warns with "declaration requires an exit-time destructor". Turn both into errors for new code and keep a reviewed allowlist for the rest. - GCC 16.2's option list has neither warning, so a project that builds with both compilers runs the check in its Clang build. - Clang's `-fno-c++-static-destructors` drops exit-time destructors for a whole translation unit or project. It is a blunt policy switch, so prefer the per-variable attribute. - Code review asks one question per new global: is it constant-initialized, and if not, who constructs it and who destroys it? ## The trade-offs to say out loud - **Lazy construction moves cost.** A function-local static adds a guard check per call and puts construction cost on whichever request arrives first; latency-sensitive code may prefer explicit warm-up from `main`. - **Never-destroyed objects lose destructor side effects.** That is right for caches and registries and wrong for anything that must flush or release external state. - **Shared libraries complicate both orders.** Loading a plugin library at runtime runs its static initializers then, not at program start, and unloading it can run its static destructors early, which is one more reason plugin registries should not depend on static construction order. - **Rules need an escape hatch.** A strict ban without an allowlist pushes people towards workarounds that hide globals; a documented exception with an owner is better. The judgment a principal shows is not knowing a trick but choosing a default that removes a class of irreproducible crashes, measuring what it costs, and making the exceptions explicit.
- Why is std::string_view a better choice than std::string for a constant global name?A `std::string_view` initialized from a string literal can be `constexpr` or `constinit` and has a trivial destructor, so it takes part in neither the startup nor the exit order. A `std::string` global has a non-trivial destructor that runs at exit, and depending on its length and the library it may need dynamic initialization too. For a fixed name the view gives the same reads with none of the ordering risk.
- How do you migrate an existing codebase that already has hundreds of non-trivial globals?Turn on `-Wglobal-constructors` and `-Wexit-time-destructors` in a Clang build, record today's hits as a baseline, and fail the build only on new ones. Then convert the globals with the most cross-file dependencies first, usually registries, loggers and configuration, to function-local statics or explicit initialization from `main`, shrinking the baseline over time.
- Banning every global is enough; function-local statics have no ordering issues at all.
- constinit makes a variable immutable, so it only suits constants.
- GCC's -Wall already warns about global constructors and exit-time destructors.
- Leaking a registry at exit is always a memory bug to be fixed.
- The order problems only exist in debug builds and vanish with optimization.
Assumes C++20 for constinit; Clang's -Wglobal-constructors, -Wexit-time-destructors and [[clang::no_destroy]] were checked on Apple clang 21, and GCC 16.2 offers neither warning.