C++: 單例模式和缺陷
睿豐德科技 專注RFID識別技術和條碼識別技術與管理軟件的集成項目。質量追溯系統、MES系統、金蝶與條碼系統對接、用友與條碼系統對接
編譯執行上面的代碼,輸出如下:
編譯上面的代碼并執行,輸出如下:
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我們發現上面的輸出并沒有調用到Singleton的虛構函數,Singleton的資源可能沒有被釋放。現在的問題是要怎么才能在程序退出的時候正確釋放Singleton的資源。我們注意到這樣一個事實:
系統會自動調用在棧和靜態數據區上分配的對象的析構函數來釋放資源。
修改程序如下:
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被明確的執行了。
相關閱讀: 遞歸模板實現單例模式 RFID管理系統集成商 RFID中間件 條碼系統中間層 物聯網軟件集成