Article

Magic statics vs. std::call_once

The Old New Thing ·The Old New Thing ·Published 2026-09-16 ·5 min read

This article discusses two methods for caching results in C++: 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


Discovered 2026-09-23 Source The Old New Thing Archive 2026-09 →