C++每日一練(20210625):梅耶的單例模式(Meyer’s Singleton)

單例模式(Singleton Pattern)

,GoF設計模式之一。保證一個類僅有一個例項,並提供一個訪問它的全域性訪問點。

C++11後執行緒安全,

保證 static local variable 在併發條件下只執行一次初始化。

參考資料:

C++ and the Perils of Double-Checked Locking

Dynamic Initialization and Destruction with Concurrency

https://www。aristeia。com/Papers/DDJ_Jul_Aug_2004_revised。pdfhttp://www。open-std。org/jtc1/sc22/wg21/docs/papers/2008/n2660。htm

#include class SA{public: SA(){std::cout << “SA” << std::endl;} void say(){ std::cout << “hello SA” << std::endl; }};class SC{public: SC(){std::cout << “SC” << std::endl;} void say(){ std::cout << “hello SC” << std::endl; }};templateclass Singleton{public: static T& getInstance() { static T value; return value; } Singleton() = delete; ~Singleton() = delete;};template class Singleton; //顯式模板例項化int main(){ std::cout << “main start” << std::endl; SA& sa = Singleton::getInstance(); SC& sc1 = Singleton::getInstance(); SC& sc2 = Singleton::getInstance(); sa。say(); sc1。say(); sc2。say();}

C++每日一練(20210625):梅耶的單例模式(Meyer’s Singleton)

線上編譯測試

https://wandbox。org/nojs/gcc-headhttps://wandbox。org/nojs/clang-headhttps://wandbox。org/permlink/2BTGHkl5UoisDuhp