码迷,mamicode.com
首页 > 编程语言 > 详细

单例模式之C++实现

时间:2014-06-26 00:06:29      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   color   

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

 

 

单例模式之C++实现,布布扣,bubuko.com

单例模式之C++实现

标签:des   style   class   blog   code   color   

原文地址:http://www.cnblogs.com/jingmoxukong/p/3804259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!