正确删除单身人士

Kam*_*Kam 1 c++ mutex

我有以下代码:

MyClass.h:

static MyMutex instanceMutex;
static MyClass* getInstance();
static void deleteInstance();
Run Code Online (Sandbox Code Playgroud)

MyClass.c:

MyMutex MyClass::instanceMutex;

MyClass* MyClass::getInstance()
{   
    if (theInstance == 0)
    {
        instanceMutex.acquire();
        if (theInstance == 0)
        {
            theInstance  = new MyClass();
        }
        instanceMutex.release();
    }
    return theInstance;
}

void MyClass::deleteInstance()
{   
    if (theInstance != 0)
    {
        instanceMutex.acquire();
        if (theInstance != 0)
        {
           theInstance->finalize();
           delete theInstance; 
           theInstance = 0;
        }
        instanceMutex.release();
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

我有2个问题:

  • 以上代码是否正确且安全?
  • 我在MyClass :: deleteInstance()中调用'delete theInstance'后,然后调用

    • theInstance = 0;
    • instanceMutex.release();

    但是,如果实例被删除,那么甚至可能?是不是班级的记忆消失了?

Gle*_*aum 13

如果它是一个单例 - 它被定义为只有一个实例 - 如果你删除它 - 它会降为0

所以看来你根本不应该支持删除