Search code examples
c++segmentation-faultsingletonstatic-order-fiasco

Overcoming static initialization order fiasco when a singleton object is involved


I have a singleton class defined in file x.h

class x
{
 public:
     static x* x_instance;
     static x* create_x_instance
     {
        if(!x_instance)
            x_instance = new x;
        return x_instance;
     }
     void someMemberFunction()
  private:
  x() { //some code}
};

extern x *x_interface;     

In x.cpp I have the following:

x *x::x_instance = 0;
x *x_interface = x::create_x_instance();   

In y.cpp, in the constructor of a another singleton class, I have

x_interface->someMemberFunction();    

I get a seg fault because y gets initialized before x. What is the correct way to solve this? I have read many articles on this, but I am still confused.


Solution

  • Just to be clear, using a static member of a static function avoids initialization order problems:

    class x
    {
     public:
         static x* get_instance()
         {
             static x* theInst = new x;
             return theInst;
         }
    
         void someMemberFunction();
      private:
         x() { //some code}
    };
    

    Later code gets x like this:

    x* handle = x::get_instance();
    

    The above is minimal, it should be further improved to manage x lifetime. It might be better to just have theImpl be a static x rather than pointer-to-x, and get_instance() return a reference instead of a pointer.