首页 > 代码库 > 单例模式之C++实现

单例模式之C++实现

#include "stdafx.h"#include <iostream>using namespace std;class Singleton{private:    static Singleton *m_instance;    Singleton()    {        cout << "Singleton Construct" << endl;    }    ~Singleton()    {        if (m_instance)        {            delete m_instance;        }        cout << "Singleton Destruct" << endl;    }public:    static Singleton* GetInstance()    {        if (!m_instance)        {            m_instance = new Singleton;        }        return m_instance;    }};Singleton* Singleton::m_instance = NULL;int main(){    //Singleton *pSingletonA = new Singleton;  //编译会报错,因为不能访问私有函数    Singleton *pSingletonA = Singleton::GetInstance();    Singleton *pSingletonB = Singleton::GetInstance();    if (pSingletonA == pSingletonB)        cout << "Same Instance" << endl;    return 0;}