标签: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的方式,更好的是,还要考虑多线程调用构造函数的事例。
标签:main with 单例 调用 exit get leo mes tor
原文地址:https://www.cnblogs.com/HaoPengZhang/p/11521317.html