静态指针 + 用到时初始化
局部静态变量
为什么叫做懒汉模式,就是不到调用getInstance函数,这个类的对象是一直不存在的
#include <iostream>
using namespace std;
class A{
public:
void setUp(){
cout<<"inside setup"<<endl;
}
A(){
cout<<"constructor called!"<<endl;
}
static A* getInstance();
static A* aa;
};
A* A::aa = nullptr;
A* A::getInstance(){
if(aa == nullptr)
aa = new A;
return aa;
}
int main(){
A* aa1 = A::getInstance();
A* aa2 = A::getInstance();
if(aa1 == aa2)
cout << "Yes" <<endl;
else
cout << "No" <<endl;
cout << "Hello world!"<<endl;
return 0;
}
#include <iostream>
using namespace std;
class A{
public:
static A& getInstance();
void setup(){
cout<<"inside setup"<<endl;
}
private:
A(){
cout<<"constructor called!"<<endl;
}
};
A& A::getInstance(){
static A a;
return a;
}
int main()
{
A a1 = A::getInstance();
A a2 = A::getInstance();
cout<<"Hello world!"<<endl;
return 0;
}
饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。故没有多线程的问题。
直接定义静态对象
静态指针 + 类外初始化时new空间实现
#include <iostream>
using namespace std;
class A{
public:
static A &getInstance(){
return aa;
}
void setup(){
cout<<"inside setup!"<<endl;
}
private:
A(){
cout<<"constructor called!"<<endl;
}
static A aa;
};
A A::aa;
int main(){
A aa1 = A::getInstance();
A aa2 = A::getInstance();
cout << "Hello world!"<<endl;
return 0;
}
#include <iostream>
using namespace std;
class A{
public:
static A* getInstance(){
return aa;
}
void setup(){
cout<<"inside setup!"<<endl;
}
private:
static A* aa;
A(){
cout<<"constructor called!"<<endl;
}
};
A* A::aa = new A;
int main()
{
A* aa1 = A::getInstance();
A* aa2 = A::getInstance();
if(aa1 == aa2)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
cout << "Hello world!"<<endl;
return 0;
}
原文:https://www.cnblogs.com/lodger47/p/14959807.html