C++單例類模板詳解
單例類
描述
指在整個系統(tǒng)生命期中,一個類最多只能有一個實(shí)例(instance)存在,使得該實(shí)例的唯一性(實(shí)例是指一個對象指針) , 比如:統(tǒng)計在線人數(shù)
在單例類里,又分為了懶漢式和餓漢式,它們的區(qū)別在于創(chuàng)建實(shí)例的時間不同:
- 懶漢式 : 指代碼運(yùn)行后,實(shí)例并不存在,只有當(dāng)需要時,才去創(chuàng)建實(shí)例(適用于單線程)
- 餓漢式 : 指代碼一運(yùn)行,實(shí)例已經(jīng)存在,當(dāng)時需要時,直接去調(diào)用即可(適用于多線程)
用法
- 將構(gòu)造函數(shù)的訪問屬性設(shè)置為private,
- 提供一個GetInstance()靜態(tài)成員函數(shù),只能供用戶訪問唯一一個實(shí)例.
- 定義一個靜態(tài)成員指針,用來供用戶獲取
- 重載 (=)賦值操作符以及拷貝構(gòu)造函數(shù),并設(shè)為private, 避免對象間拷貝,復(fù)制.
初探單例類-懶漢式:
#include <iostream>
using namespace std;
class CSingleton
{
private:
static CSingleton* m_pInstance;
CSingleton() //構(gòu)造函數(shù)為private
{
}
CSingleton& operator = (const CSingleton& t);
CSingleton(const CSingleton &);
public:
static CSingleton* getInstance()
{
if(m_pInstance==NULL)
m_pInstance= new CSingleton();
return m_pInstance;
}
void print()
{
cout<<this<<endl;
}
};
CSingleton* CSingleton::m_pInstance = NULL;
int main()
{
CSingleton *p1=CSingleton::getInstance();
CSingleton *p2=CSingleton::getInstance();
CSingleton *p3=CSingleton::getInstance();
p1->print();
p2->print();
p3->print();
return 0;
}
運(yùn)行打印:
0x6e2d18
0x6e2d18
0x6e2d18
從打印結(jié)果可以看出,該指針對象指向的都是同一個地址,實(shí)現(xiàn)了一個類最多只能有一個實(shí)例(instance)存在.
注意:由于實(shí)例(instance),在系統(tǒng)生命期中,都是存在的,所以只要系統(tǒng)還在運(yùn)行,就不需要delete
上面的懶漢式如果在多線程情況下 ,多個Csingleton指針對象同時調(diào)用getInstance()成員函數(shù)時,由于m_pInstance = NULL,就會創(chuàng)建多個實(shí)例出來.
所以,在多線程情況下,需要使用餓漢實(shí)現(xiàn)
代碼如下:
class CSingleton
{
private:
static CSingleton* m_pInstance;
CSingleton() //構(gòu)造函數(shù)為private
{
}
CSingleton& operator = (const CSingleton& t);
CSingleton(const CSingleton &);
public:
static CSingleton* getInstance()
{
return m_pInstance;
}
};
CSingleton* CSingleton::m_pInstance = new CSingleton;
單例類模板
我們現(xiàn)在講解的僅僅是個框架,里面什么都沒有,不能滿足需求啊,所以還要寫為單例類模板頭文件,當(dāng)需要單例類時,直接聲明單例類模板頭文件即可
寫CSingleton.h
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
template <typename T>
class CSingleton
{
private:
static T* m_pInstance;
CSingleton() //構(gòu)造函數(shù)為private
{
}
public:
static T* getInstance()
{
return m_pInstance;
}
};
template <typename T>
T* CSingleton<T> :: m_pInstance = new T;
#endif
當(dāng)我們需要這個單例類模板時,只需要在自己類里通過friend添加為友元即可,
接下來試驗(yàn)單例類模板
寫main.cpp
#include <iostream>
#include <string>
#include "CSingleton.h"
using namespace std;
class Test
{
friend class CSingleton<Test> ; //聲明Test的友元為單例類模板
private:
string mstr;
Test(): mstr("abc")
{
}
Test& operator = (const Test& t);
Test(const Test&);
public:
void Setmstr(string t)
{
mstr=t;
}
void print()
{
cout<<"mstr = "<<mstr<<endl;
cout<<"this = "<<this<<endl;
}
};
int main()
{
Test *pt1 = CSingleton<Test>::getInstance();
Test *pt2 = CSingleton<Test>::getInstance();
pt1->print();
pt2->print();
pt1->Setmstr("ABCDEFG");
pt2->print();
return 0;
}
mstr = abc
this = 0x2d2e30mstr = abc
this = 0x2d2e30mstr = ABCDEFG
this = 0x2d2e30
以上所述是小編給大家介紹的C++單例類模板詳解整合,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Qt+OpenCV利用幀差法實(shí)現(xiàn)車輛識別

