单例模式是一种设计模式,确保一个类只有一个实例,并提供一个全局访问点。

懒汉模式(Meyers’ Singleton)

1
2
3
4
5
6
7
8
9
10
11
12
class Singleton{
public:
static Singleton& getInstance(){
static Singleton obj; // 静态局部变量
return obj;
}
Singleton(const Singleton&) = delete; // 显示拒绝拷贝构造和复制构造
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
~Singleton() = default;
};

通用化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template<typename T>
class Singleton
{
public:
static T& getInstance() {
static T t;
return t;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
~Singleton() = default;
};

饿汉模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Singleton
{
public:
static Singleton& getInstance()
{
return instance;
}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() = default;
~Singleton() = default;
private:
static Singleton instance;
};
Singleton Singleton::instance;