# 单例模式
线程安全的单例模式(C++11),C++11 标准规定: static local 的变量会保证初始化一次,并且是多线程安全的。由此我们可以得到这样的单例实现。
class Singleton
{
public:
static Singleton &get_instance()
{
static Singleton instance;
return instance;
}
private:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton &operator=(Singleton &&) = delete;
};
// 进行初始化的传参
#include <iostream>
class Singleton
{
public:
static Singleton &get_instance()
{
static Singleton instance(param);
return instance;
}
static int param;
int storage;
private:
Singleton(int m) : storage(m) {}
~Singleton() = default;
Singleton(const Singleton &) = delete;
Singleton(Singleton &&) = delete;
Singleton &operator=(const Singleton &) = delete;
Singleton &operator=(Singleton &&) = delete;
};
int Singleton::param = 0;
int main(int argc, char **arg)
{
Singleton::param = 1;
std::cout << Singleton::get_instance().storage;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52