I've been thinking about an alternative to LazyInstance and NoDestructor for a while now that would be both single-line init (like LazyInstance) and non-destroyed in prod (like NoDestructor) but also provide constexpr-init for types that support it and be resettable for tests (we've seen numerous issues with singletons that leak state from one test to the next -- test retries often hide this). Should write it up into a doc... but here it goes in short:
LAZY_INIT_GLOBAL(var_type, var_name)
CONST_INIT_GLOBAL(
var_type, var_name
)
CONST_INIT_GLOBAL is equivalent to LAZY_INIT_GLOBAL by default but when compiling under Clang it can use [[clang::require_constant_initialization]] as an optimization.
and
LAZY_INIT_GLOBAL is:
#define LAZY_INIT_GLOBAL(var_type, var_name) \
struct { \
var_type& operator*() { \
static RegisteredGlobal<var_type> instance; \
return *instance; \
} \
} var_name
Then *var_name is all that's needed to access the global; could also expose operator->() for consistency.
RegisteredGlobal<var_type> works like the lazy_task_runner.h logic; it's registered into a void in prod. But in tests we keep track of instances and recycle them between tests.