单例模式

单例模式就是该类只允许有一个类实例,如下示例一,是一个常见的实现方式。

示例一:该实现需要手动去销毁实例(实际使用中,常常忘记调用DestroyInstance()销毁实例)

class Singleton
{
public:
    static Singleton* GetInstance() 
    {
        if (nullptr == m_instance)
        {
            m_instance = new Singleton();
        }
        
        return m_instance;
    }

    static DestroyInstance()
    {
        if (nullptr != m_instance)
        {
            delete m_instance;
            m_instance = nullptr;
        }
    }
private:
    Singleton(){}
    static Singleton* m_instance;
};

Singleton* Singleton::m_instance = nullptr;

示例二:该实现程序结束时,系统会调用该类的析构函数,销毁实例

class Singleton
{
public:
    static Singleton* GetInstance() 
    {
        static Singleton instance;       
        return &instance;
    }
private:
   Singleton(){} 
};

备注:c++0x后不用考虑多线程的问题,由编译器保证静态变量的线程安全性。

在孤独中思考,在思考中成熟,在成熟中升华
原文地址:https://www.cnblogs.com/laogaoyang/p/5853285.html