Properly deleting a singleton

前端 未结 5 831
悲&欢浪女
悲&欢浪女 2021-01-24 23:07

I have the following code:

MyClass.h:

static MyMutex instanceMutex;
static MyClass* getInstance();
static void deleteInstance();

MyClas

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 23:36

    Here be a problem:

    if (theInstance == 0)  // <- Some other thread might see a non-null theInstance 
    {                      // before the constructor below returns
    
        instanceMutex.acquire();
        if (theInstance == 0)
        {
            theInstance  = new MyClass();  // <- This might set theInstance to something 
                                           // before the constructor returns.
        }
        instanceMutex.release();
    }
    

    You may want to implement some sort of reference counting system (like using shared_ptr) and initializing it in a similar manner, though taking care to ensure that its instance pointer is not set before the initialization completes.

    If you are feeling adventurous, you could also try:

    if (theInstance == 0)
    {
        instanceMutex.acquire();
        if (theInstance == 0)
        {
            MyClass * volatile ptr = new MyClass();
            __FuglyCompilerSpecificFenceHintThatMightNotActuallyDoAnything();
            theInstance = ptr;  // <- Much hilarity may ensue if this write is not atomic.
        }
        instanceMutex.release();
    }
    

    This might fix it, and it might not. In the second case, it depends on how your compiler handles volatile, and weather or not pointer-sized writes are atomic.

提交回复
热议问题