C++ 单例模式

2014-11-24 01:32:55 · 作者: · 浏览: 2
一、整体代码
01.cpp
#include   
using namespace std;  
class Singleton  
{  
public:  
    static Singleton* GetInstance()  
    {  
        if (instacne_ == NULL)  
        {  
            instacne_ = new Singleton;  
        }  
        return instacne_;  
    }  
    ~Singleton()  
    {  
        cout<<"~Singleton ..."<
02.cpp
#include   
using namespace std;  
class Singleton  
{  
public:  
    static Singleton& GetInstance()  
    {  
        static Singleton instance;  
        return instance;  
    }  
    ~Singleton()  
    {  
        cout<<"~Singleton ..."< 
  

二、解释
第一种方式是在堆空间分配了内存,所以又创建了在栈空间建立了了一个Garbo变量,利用它的确定析构性来释放刚才在堆空间占用的内存。
第二种方式直接在栈空间分配了内存,函数结束后自动释放。