- 单例在内存中只有一份,在内存中不会占用太多,程序退出时会随着程序统一释放内存,所以可以不必特意释放
一、懒汉式
不是线程安全的,所以多线程使用要加锁
class Singleton{
public:
static Singleton* getInstance(){
if(s_instance == nullptr){
s_instance = new Singleton;
}
return s_instance;
}
// 可有可无,程序结束时,系统会自动回收程序的所有内存
class Garbo{
~Garbo(){
if(s_instance){
cout << "gc..." << endl;
delete s_instance;
}
}
};
private:
Singleton(){
cout << "Singleton()..." << endl;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* s_instance;
static Garbo s_gc;
};
Singleton* Singleton::s_instance = nullptr;
int main()
{
cout << "main()..." << endl;
Singleton* s = Singleton::getInstance();
return 0;
}
输出:
main()...
Singleton()...
二、饿汉式
在 main 函数之前,单例就创建好了,所以是线程安全的
class Singleton{
public:
static Singleton* getInstance(){
return s_instance;
}
private:
Singleton(){
cout << "Singleton()..." << endl;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static Singleton* s_instance;
};
Singleton* Singleton::s_instance = new Singleton;
int main()
{
cout << "main()..." << endl;
Singleton* s = Singleton::getInstance();
return 0;
}
输出:
Singleton()...
main()...
三、更加简单的方式
class Singleton{
public:
static Singleton* getInstance(){
static Singleton* s_instance = new Singleton;
return s_instance;
}
void sayHello(){
cout << "Hi there" << endl;
}
private:
Singleton(){
cout << "Singleton()..." << endl;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
int main()
{
cout << "main()..." << endl;
Singleton* s1 = Singleton::getInstance();
cout << s1 << endl;
s1->sayHello();
Singleton* s2 = Singleton::getInstance();
cout << s2 << endl;
s2->sayHello();
return 0;
}
输出:
main()...
Singleton()...
0x55cc7de532c0
Hi there
0x55cc7de532c0
Hi there