c++ - 正确删除单例

标签 c++ mutex

我有以下代码:

我的类.h:

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

我的类.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”后,我调用

    • 实例 = 0;
    • instanceMutex.release();

    但如果实例被删除,那怎么可能呢?类的内存是不是没有了?

最佳答案

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

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

关于c++ - 正确删除单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20106516/

相关文章:

c++ - 将派生类型的对象从 python 传递到期望 shared_ptr 为基类型的 C++ 函数时,Boost Python 运行时错误

c++ - C++中结构对象的深拷贝指针

C编程中的并发线程

c++ - C++ 程序没有输出

c++ - 五子棋对角线获胜条件

c++ - Do-while 循环不会退出 C++

c++ - 如何使用内联汇编模拟以下 C++ 代码?

c++ - boost 互斥锁

c - 全局/本地/静态互斥锁的区别?

函数可以锁定互斥量吗?