C++ : non-local static object initialization problem

If one global object is directly dependent on another global object, the order of their construction is undefined. The best solution for it, suggested by Scott Meyers is to use singletons : ( see : Scott Meyers "Item 47: Ensure that non-local static objects are initialized before they're used." Effective C++ )

The basis of this approach is the observation that although C++ says next to nothing about when a nonlocal static object is initialized, it specifies quite precisely when a static object inside a function (i.e. a local static object) is initialized: it's when the object's definition is first encountered during a call to that function. So if you replace direct accesses to non-local static objects with calls to functions that return references to local static objects inside them, you're guaranteed that the references you get back from the functions will refer to initialized objects. As a bonus, if you never call a function emulating a nonlocal
static object, you never incur the cost of constructing and destructing the object, something that can't be said for true non-local static objects

No comments: