正确删除单例 [英] Properly deleting a singleton

查看:120
本文介绍了正确删除单例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

MyClass.h:

MyClass.h:

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

MyClass.c:

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;
}

我有两个问题:

在MyClass :: deleteInstance()中调用delete theInstance之后,然后我调用

  • Is the above code correct and safe?
  • After I call 'delete theInstance' in MyClass::deleteInstance(), I then call


  • theInstance = 0;

  • instanceMutex.release();

但是如果实例被删除,那么怎么可能呢?

But if the instance is deleted than how is that even possible? isn't the memory of the class gone?

推荐答案

singleton - 它被定义为只有一个实例 - 如果你删除它 - 这降到0

If it's a singleton - it is defined to have exactly one instance - if you delete it - this drops to 0

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

So it seems you should not support delete at all

这篇关于正确删除单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆