首页 / C++ / C++: 单例模式和缺陷
C++: 单例模式和缺陷
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++: 单例模式和缺陷,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2015字,纯文字阅读大概需要3分钟。
内容图文
![C++: 单例模式和缺陷](/upload/InfoBanner/zyjiaocheng/1206/fb67668f3f7e41a3b787533da4c32ef9.jpg)
C++: 单例模式和缺陷
实现一个单例模式
1
|
class
Singleton {
|
2
|
private
:
|
3
|
Singleton() { cout <<
"Singleton::constructor"
<< endl; }
|
4
|
~Singlton() { cout <<
"Singleton::destructor"
<< endl; }
|
5
|
Singleton(
const
Singleton&) {};
|
6
|
Singleton &operator=(
const
Singleton&) {};
|
7
|
public
:
|
8
|
static
Singleton* getInstance() {
|
9
|
if
(m_aInstance == NULL) {
|
10
|
m_aInstance =
new
Singleton();
|
11
|
}
|
12
|
return
m_aInstance;
|
13
|
}
|
14
|
void
show() {
|
15
|
cout <<
"Singleton::show"
<< endl;
|
16
|
}
|
17
|
private
:
|
18
|
static
Singleton* m_aInstance;
|
19
|
};
|
20
|
21
|
Singleton* Singleton::m_aInstance = NULL;
|
22
|
23
|
int
main(
int
argc,
char
**argv) {
|
24
|
Singleton* aSingleton = Singleton::getInstance();
|
25
|
aSingleton->show();
|
26
|
return
0;
|
27
|
}
|
Singleton::constructor Singleton::show
系统会自动调用在栈和静态数据区上分配的对象的析构函数来释放资源。
修改程序如下:
1 | class Singleton { |
2 | private : |
3 | Singleton() { cout << "Singleton::constructor" << endl; } |
4 | ~Singleton() { cout << "Singleton::destructor" << endl; } |
5 | Singleton( const Singleton&) {}; |
6 | Singleton &operator=( const Singleton&) {}; |
7 | public : |
8 | static Singleton* getInstance() { |
9 | if (m_aInstance == NULL) { |
10 | m_aInstance = new Singleton(); |
11 | } |
12 | return m_aInstance; |
13 | } |
14 | void show() { |
15 | cout << "Singleton::show" << endl; |
16 | } |
17 |
18 | private : |
19 | class Garbage{ |
20 | public : |
21 | ~Garbage() { |
22 | if (m_aInstance != NULL) { |
23 | delete m_aInstance; |
24 | } |
25 | } |
26 | }; |
27 | |
28 | private : |
29 | static Singleton* m_aInstance; |
30 | static Garbage m_garbage; |
31 | }; |
32 |
33 | Singleton* Singleton::m_aInstance = NULL; |
34 | Singleton::Garbage Singleton::m_garbage; |
35 |
36 | int main( int argc, char **argv) { |
37 | Singleton* aSingleton = Singleton::getInstance(); |
38 | aSingleton->show(); |
39 | return 0; |
40 | } |
Singleton::constructor Singleton::show Singleton::destructor
我们看到Singleton::destructor被明确的执行了。
原文:http://www.cnblogs.com/lidabo/p/3701101.html
内容总结
以上是互联网集市为您收集整理的C++: 单例模式和缺陷全部内容,希望文章能够帮你解决C++: 单例模式和缺陷所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。