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

C++实现单例

时间:2019-09-15 11:19:02      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:main   with   单例   调用   exit   get   leo   mes   tor   

实现代码如下

#include <iostream>
using namespace std;
class Singleon{
private:
    Singleon(){
    cout<<"调用构造函数了"<<endl;
}
    static Singleon* instance;
public:
    static Singleon * getInstance(){
        return instance;
    }
    static Singleon * initInstance(){
        if(instance==nullptr){
            instance=new Singleon();
        }else{
            cout<<"已经创造过对象了,没有再创建"<<endl;
        }
        return instance;
    }
    static void Destory(){
        delete instance;
        instance=nullptr;
    }
};
Singleon *Singleon::instance = nullptr;
int main()
{
    Singleon *s1=Singleon::initInstance();
    Singleon *s2=Singleon::initInstance();
    Singleon *s3=Singleon::initInstance();
    cout<<s1<<endl;
    cout<<s2<<endl;
    cout<<s3<<endl;
}

运行结果

调用构造函数了
已经创造过对象了,没有再创建
已经创造过对象了,没有再创建
0x10120e750
0x10120e750
0x10120e750
Program ended with exit code: 0

值得说明的是,这个是最low的方式,更好的是,还要考虑多线程调用构造函数的事例。

C++实现单例

标签:main   with   单例   调用   exit   get   leo   mes   tor   

原文地址:https://www.cnblogs.com/HaoPengZhang/p/11521317.html

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