網(wǎng)站首頁 編程語言 正文
局部靜態(tài)變量方式
//通過靜態(tài)成員變量實現(xiàn)單例 //懶漢式 class Single2 { private: Single2() { } Single2(const Single2 &) = delete; Single2 &operator=(const Single2 &) = delete; public: static Single2 &GetInst() { static Single2 single; return single; } };
上述代碼通過局部靜態(tài)成員single實現(xiàn)單例類,原理就是函數(shù)的局部靜態(tài)變量生命周期隨著進(jìn)程結(jié)束而結(jié)束。上述代碼通過懶漢式的方式實現(xiàn)。
調(diào)用如下
void test_single2() { //多線程情況下可能存在問題 cout << "s1 addr is " << &Single2::GetInst() << endl; cout << "s2 addr is " << &Single2::GetInst() << endl; }
程序輸出如下
sp1 ?is ?0x1304b10
sp2 ?is ?0x1304b10
確實生成了唯一實例,上述單例模式存在隱患,對于多線程方式生成的實例可能時多個。
靜態(tài)成員變量指針方式
可以定義一個類的靜態(tài)成員變量,用來控制實現(xiàn)單例
//餓漢式 class Single2Hungry { private: Single2Hungry() { } Single2Hungry(const Single2Hungry &) = delete; Single2Hungry &operator=(const Single2Hungry &) = delete; public: static Single2Hungry *GetInst() { if (single == nullptr) { single = new Single2Hungry(); } return single; } private: static Single2Hungry *single; };
這么做的一個好處是我們可以通過餓漢式的方式避免線程安全問題
//餓漢式初始化 Single2Hungry *Single2Hungry::single = Single2Hungry::GetInst(); void thread_func_s2(int i) { cout << "this is thread " << i << endl; cout << "inst is " << Single2Hungry::GetInst() << endl; } void test_single2hungry() { cout << "s1 addr is " << Single2Hungry::GetInst() << endl; cout << "s2 addr is " << Single2Hungry::GetInst() << endl; for (int i = 0; i < 3; i++) { thread tid(thread_func_s2, i); tid.join(); } } int main(){ test_single2hungry() }
程序輸出如下
s1 addr is 0x1e4b00
s2 addr is 0x1e4b00
this is thread 0
inst is 0x1e4b00
this is thread 1
inst is 0x1e4b00
this is thread 2
inst is 0x1e4b00
可見無論單線程還是多線程模式下,通過靜態(tài)成員變量的指針實現(xiàn)的單例類都是唯一的。餓漢式是在程序啟動時就進(jìn)行單例的初始化,這種方式也可以通過懶漢式調(diào)用,無論餓漢式還是懶漢式都存在一個問題,就是什么時候釋放內(nèi)存?多線程情況下,釋放內(nèi)存就很難了,還有二次釋放內(nèi)存的風(fēng)險。
我們定義一個單例類并用懶漢式方式調(diào)用
//懶漢式指針 //即使創(chuàng)建指針類型也存在問題 class SinglePointer { private: SinglePointer() { } SinglePointer(const SinglePointer &) = delete; SinglePointer &operator=(const SinglePointer &) = delete; public: static SinglePointer *GetInst() { if (single != nullptr) { return single; } s_mutex.lock(); if (single != nullptr) { s_mutex.unlock(); return single; } single = new SinglePointer(); s_mutex.unlock(); return single; } private: static SinglePointer *single; static mutex s_mutex; };
在cpp文件里初始化靜態(tài)成員,并定義一個測試函數(shù)
//懶漢式 //在類的cpp文件定義static變量 SinglePointer *SinglePointer::single = nullptr; std::mutex SinglePointer::s_mutex; void thread_func_lazy(int i) { cout << "this is lazy thread " << i << endl; cout << "inst is " << SinglePointer::GetInst() << endl; } void test_singlelazy() { for (int i = 0; i < 3; i++) { thread tid(thread_func_lazy, i); tid.join(); } //何時釋放new的對象?造成內(nèi)存泄漏 } int main(){ test_singlelazy(); }
函數(shù)輸出如下
this is lazy thread 0 inst is 0xbc1700 this is lazy thread 1 inst is 0xbc1700 this is lazy thread 2 inst is 0xbc1700
此時生成的單例對象的內(nèi)存空間還沒回收,這是個問題,另外如果多線程情況下多次delete也會造成崩潰。
智能指針方式
可以利用智能指針自動回收內(nèi)存的機(jī)制設(shè)計單例類
//利用智能指針解決釋放問題 class SingleAuto { private: SingleAuto() { } SingleAuto(const SingleAuto &) = delete; SingleAuto &operator=(const SingleAuto &) = delete; public: ~SingleAuto() { cout << "single auto delete success " << endl; } static std::shared_ptrGetInst() { if (single != nullptr) { return single; } s_mutex.lock(); if (single != nullptr) { s_mutex.unlock(); return single; } single = std::shared_ptr (new SingleAuto); s_mutex.unlock(); return single; } private: static std::shared_ptr single; static mutex s_mutex; };
SingleAuto的GetInst返回std::shared_ptr類型的變量single。因為single是靜態(tài)成員變量,所以會在進(jìn)程結(jié)束時被回收。智能指針被回收時會調(diào)用內(nèi)置指針類型的析構(gòu)函數(shù),從而完成內(nèi)存的回收。
在主函數(shù)調(diào)用如下測試函數(shù)
// 智能指針方式 std::shared_ptrSingleAuto::single = nullptr; mutex SingleAuto::s_mutex; void test_singleauto() { auto sp1 = SingleAuto::GetInst(); auto sp2 = SingleAuto::GetInst(); cout << "sp1 is " << sp1 << endl; cout << "sp2 is " << sp2 << endl; //此時存在隱患,可以手動刪除裸指針,造成崩潰 // delete sp1.get(); } int main(){ test_singleauto(); }
程序輸出如下
sp1 ?is ?0x1174f30
sp2 ?is ?0x1174f30
智能指針方式不存在內(nèi)存泄漏,但是有一個隱患就是單例類的析構(gòu)函數(shù)時public的,如果被人手動調(diào)用會存在崩潰問題,比如將上邊test_singleauto中的注釋打開,程序會崩潰。
輔助類智能指針單例模式
智能指針在構(gòu)造的時候可以指定刪除器,所以可以傳遞一個輔助類或者輔助函數(shù)幫助智能指針回收內(nèi)存時調(diào)用我們指定的析構(gòu)函數(shù)。
// safe deletor //防止外界delete //聲明輔助類 //該類定義仿函數(shù)調(diào)用SingleAutoSafe析構(gòu)函數(shù) //不可以提前聲明SafeDeletor,編譯時會提示incomplete type // class SafeDeletor; //所以要提前定義輔助類 class SingleAutoSafe; class SafeDeletor { public: void operator()(SingleAutoSafe *sf) { cout << "this is safe deleter operator()" << endl; delete sf; } }; class SingleAutoSafe { private: SingleAutoSafe() {} ~SingleAutoSafe() { cout << "this is single auto safe deletor" << endl; } SingleAutoSafe(const SingleAutoSafe &) = delete; SingleAutoSafe &operator=(const SingleAutoSafe &) = delete; //定義友元類,通過友元類調(diào)用該類析構(gòu)函數(shù) friend class SafeDeletor; public: static std::shared_ptrGetInst() { if (single != nullptr) { return single; } s_mutex.lock(); if (single != nullptr) { s_mutex.unlock(); return single; } //額外指定刪除器 single = std::shared_ptr (new SingleAutoSafe, SafeDeletor()); //也可以指定刪除函數(shù) // single = std::shared_ptr (new SingleAutoSafe, SafeDelFunc); s_mutex.unlock(); return single; } private: static std::shared_ptr single; static mutex s_mutex; };
SafeDeletor要寫在SingleAutoSafe上邊,并且SafeDeletor要聲明為SingleAutoSafe類的友元類,這樣就可以訪問SingleAutoSafe的析構(gòu)函數(shù)了。
我們在構(gòu)造single時制定了SafeDeletor(),single在回收時,會調(diào)用SingleAutoSafe的仿函數(shù),從而完成內(nèi)存的銷毀。
并且SingleAutoSafe的析構(gòu)函數(shù)為私有的無法被外界手動調(diào)用了。
//智能指針初始化為nullptr std::shared_ptrSingleAutoSafe::single = nullptr; mutex SingleAutoSafe::s_mutex; void test_singleautosafe() { auto sp1 = SingleAutoSafe::GetInst(); auto sp2 = SingleAutoSafe::GetInst(); cout << "sp1 is " << sp1 << endl; cout << "sp2 is " << sp2 << endl; //此時無法訪問析構(gòu)函數(shù),非常安全 // delete sp1.get(); } int main(){ test_singleautosafe(); }
程序輸出如下
sp1 is 0x1264f30 sp2 is 0x1264f30
通過輔助類調(diào)用單例類的析構(gòu)函數(shù)保證了內(nèi)存釋放的安全性和唯一性。這種方式時生產(chǎn)中常用的。如果將test_singleautosafe函數(shù)的注釋打開,手動delete sp1.get()編譯階段就會報錯,達(dá)到了代碼安全的目的。因為析構(gòu)被設(shè)置為私有函數(shù)了。
通用的單例模板類
我們可以通過聲明單例的模板類,然后繼承這個單例模板類的所有類就是單例類了。達(dá)到泛型編程提高效率的目的。
templateclass Single_T { protected: Single_T() = default; Single_T(const Single_T &st) = delete; Single_T &operator=(const Single_T &st) = delete; ~Single_T() { cout << "this is auto safe template destruct" << endl; } public: static std::shared_ptr GetInst() { if (single != nullptr) { return single; } s_mutex.lock(); if (single != nullptr) { s_mutex.unlock(); return single; } //額外指定刪除器 single = std::shared_ptr (new T, SafeDeletor_T ()); //也可以指定刪除函數(shù) // single = std::shared_ptr (new SingleAutoSafe, SafeDelFunc); s_mutex.unlock(); return single; } private: static std::shared_ptr single; static mutex s_mutex; }; //模板類的static成員要放在h文件里初始化 template std::shared_ptr Single_T ::single = nullptr; template mutex Single_T ::s_mutex;
我們定義一個網(wǎng)絡(luò)的單例類,繼承上述模板類即可,并將構(gòu)造和析構(gòu)設(shè)置為私有,同時設(shè)置友元保證自己的析構(gòu)和構(gòu)造可以被友元類調(diào)用.
//通過繼承方式實現(xiàn)網(wǎng)絡(luò)模塊單例 class SingleNet : public Single_T{ private: SingleNet() = default; SingleNet(const SingleNet &) = delete; SingleNet &operator=(const SingleNet &) = delete; ~SingleNet() = default; friend class SafeDeletor_T ; friend class Single_T ; };
在主函數(shù)中調(diào)用如下
void test_singlenet() { auto sp1 = SingleNet::GetInst(); auto sp2 = SingleNet::GetInst(); cout << "sp1 is " << sp1 << endl; cout << "sp2 is " << sp2 << endl; }
程序輸出如下
sp1 ?is ?0x1164f30
sp2 ?is ?0x1164f30
總結(jié)
原文鏈接:https://blog.csdn.net/secondtonone1/article/details/123616175
相關(guān)推薦
- 2023-08-13 為什么Git需要配置ssh密鑰,怎么配置?
- 2022-10-12 深入淺出Golang中select的實現(xiàn)原理_Golang
- 2022-10-17 Net?core中使用System.Drawing對上傳的圖片流進(jìn)行壓縮(示例代碼)_實用技巧
- 2022-07-07 redis遠(yuǎn)程連接不上的解決辦法_Redis
- 2022-08-05 利用Python?list列表修改元素_python
- 2022-02-28 gyp info it worked if it ends with ok npm ERR 解決辦法
- 2022-10-08 C語言實現(xiàn)影院管理系統(tǒng)程序設(shè)計_C 語言
- 2022-07-20 C語言深入刨析數(shù)據(jù)結(jié)構(gòu)之棧與鏈棧的設(shè)計與應(yīng)用_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支