餓漢式

#include <iostream>
using namespace std;
class A{
public:
static A& getInstance(void){
return s_instance;
}
private:
A(int data=0):m_data(data){}
A(A const& that);
int m_data;
static A s_instance;
};
A A::s_instance(1234);
int main(void){
A& a1 = A::getInstance();
A& a2 = A::getInstance();
cout << &a1 << ',' << &a2 << endl;
return 0;
}這個(gè)是以靜態(tài)成員作為單例的。
因?yàn)槭菃卫?所以禁止創(chuàng)建其他A類對(duì)象,A a調(diào)用構(gòu)造函數(shù)創(chuàng)建對(duì)象,所以將A類的構(gòu)造函數(shù)放在
private里,A a = A::getInstance()調(diào)用拷貝構(gòu)造函數(shù)創(chuàng)建對(duì)象,所以將拷貝構(gòu)造函數(shù)放在private里
面,同時(shí)接口函數(shù)static A& getInstance(void),是靜態(tài)的,如果是非靜態(tài)的,那么怎么調(diào)用getInstance
函數(shù)呢,所以必須是靜態(tài)的.
注意:靜態(tài)成員對(duì)象s_instance是可以調(diào)用私有的構(gòu)造函數(shù)的(我也不知道為什么).
2.懶漢式
#include <iostream>
using namespace std;
class A{
public:
static A& getInstance(void){
if(!s_instance){
s_instance = new A(1234);
}
return *s_instance;
}
void release(void){
if(s_counter && --s_counter==0){
delete this;
s_instance = NULL;
}
}
private:
~A(void){}
A(int data = 0):m_data(data){}
A(A const& that);
int m_data;
static int s_counter;
static A* s_instance;
};
int A::s_counter = 0;
A* A::s_instance = NULL;
int main(void){
A& a1 = A::getInstance();
A& a2 = A::getInstance();
cout << &a1 << ',' << &a1 << endl;
a1.release();
a2.release();
return 0;
}這里是以靜態(tài)成員指針作為單例,也沒什么好說的了.
注意:靜態(tài)成員指針s_instance,在new A(1234)時(shí)調(diào)用構(gòu)造函數(shù),但是在delete this時(shí),是不會(huì)調(diào)用析夠函數(shù)的,不管是公有的析構(gòu)函數(shù)還是私有的析構(gòu)函數(shù)(為什么不能調(diào)用析構(gòu)函數(shù)我也不知道)
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
當(dāng)前文章:C++兩種單例(餓漢式,懶漢式)-創(chuàng)新互聯(lián)
本文來源:http://www.chinadenli.net/article22/dioejc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、軟件開發(fā)、品牌網(wǎng)站建設(shè)、App開發(fā)、網(wǎng)站制作、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容