forked from JiauZhang/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleton.cpp
76 lines (66 loc) · 2.38 KB
/
singleton.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Copyright(c) 2019 Jiau Zhang
* For more information see <https://github.com/JiauZhang/algorithms>
*
* This repo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation
*
* It is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with THIS repo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
using namespace std;
class singleton_v1
{
public:
int data_test;
static singleton_v1& getInstance() {
static singleton_v1 singleton;
return singleton;
}
private:
singleton_v1() {}
};
int main(int argc, char** argv)
{
//使用返回值得引用才会发生使用的是同一个类实例
cout << "mysingleton1: ";
singleton_v1& mysingleton1 = singleton_v1::getInstance();
mysingleton1.data_test = 0;
cout << mysingleton1.data_test << ' ';
mysingleton1.data_test++;
cout << mysingleton1.data_test << '\n';
cout << "mysingleton2: ";
singleton_v1& mysingleton2 = singleton_v1::getInstance();
cout << mysingleton2.data_test << ' ';
mysingleton2.data_test++;
cout << mysingleton2.data_test << '\n';
//直接将返回值赋值给声明的类变量,并不会使用同一个类的实例
cout << "mysingleton3: ";
singleton_v1 mysingleton3 = singleton_v1::getInstance();
cout << mysingleton3.data_test << ' ';
mysingleton3.data_test++;
cout << mysingleton3.data_test << '\n';
cout << "mysingleton4: ";
singleton_v1 mysingleton4 = singleton_v1::getInstance();
cout << mysingleton4.data_test << ' ';
mysingleton4.data_test++;
cout << mysingleton4.data_test << ' ';
cout << mysingleton4.data_test << ' ';
mysingleton4.data_test++;
cout << mysingleton4.data_test << '\n';
cout << "mysingleton1: " << mysingleton1.data_test << '\n';
cout << "mysingleton2: " << mysingleton2.data_test << '\n';
cout << "mysingleton3: " << mysingleton3.data_test << '\n';
cout << "mysingleton4: " << mysingleton4.data_test << '\n';
//从输出可以看出,实例1和实例2操作的是同一个实例
//而实例3和实例4是实例1和实例2共同指向的实例的副本,并且各自有自己的数据
//所以,只有使用类返回的引用才可以使用同一个类实例
return 0;
}