Search code examples
c++static-memberslazy-initialization

Is there a way of lazy initializing a static sub-object of a class?


Is there a way of initializing a static class member after main() has started ?


Solution

  • One way to do that is to replace the static member data which static member function.

    Say you've this class:

    class A
    {
       static B static_b; //static member data
    };
    
    //.cpp
    B A::static_b; //definition (required)
    

    So instead of that you can define your class as:

    class A
    {
       static B static_b()  //static member function!
       {
           static B b;
           return b;
       }
    };
    

    Note that it is not thread-safe, but you can make it thread-safe as well.