Magic statics vs. std::call_once
cppdashboard.dev/r/2026/09/magic-statics-vs-std-call-onceThis article discusses two methods for caching the result of a function that checks OS features: using magic statics and std::call_once. It compares their convenience and accessibility across multiple functions.
From the article
bool should_use_widgets() { bool supported = ⟦ complex code to check OS features ⟧; return supported && is_configuration_enabled("widgets"); } Since OS Widget support is not something that changes during the lifetime of the program, you want to calculate it once and cache the result.
One way is to use a so-called “magic static”:
bool should_use_widgets() { static const bool supported = [] { return ⟦ complex code to check OS features ⟧; }(); return supported && is_configuration_enabled("widgets"); } Function-local statics are initialized the first time execution reaches the variable. On subsequent executions, nothing happens.
Share this resource