diff --git a/design_pattern/singleton/README.md b/design_pattern/singleton/README.md index 4601823..b91b82e 100644 --- a/design_pattern/singleton/README.md +++ b/design_pattern/singleton/README.md @@ -114,7 +114,7 @@ private: static singleton *p; static mutex lock_; public: - singleton *instance(); + static singleton *instance(); // 实现一个内嵌垃圾回收类 class CGarbo @@ -131,6 +131,7 @@ public: singleton *singleton::p = nullptr; singleton::CGarbo Garbo; +std::mutex singleton::lock_; singleton* singleton::instance() { if (p == nullptr) { diff --git a/design_pattern/singleton/dcl_singleton.cpp b/design_pattern/singleton/dcl_singleton.cpp index 88278bb..2b22d03 100644 --- a/design_pattern/singleton/dcl_singleton.cpp +++ b/design_pattern/singleton/dcl_singleton.cpp @@ -14,7 +14,7 @@ private: static singleton *p; static mutex lock_; public: - singleton *instance(); + static singleton *instance(); // 实现一个内嵌垃圾回收类 class CGarbo @@ -31,6 +31,7 @@ public: singleton *singleton::p = nullptr; singleton::CGarbo Garbo; +std::mutex singleton::lock_; singleton* singleton::instance() { if (p == nullptr) { diff --git a/design_pattern/singleton/static_local_singleton.cpp b/design_pattern/singleton/static_local_singleton.cpp index ddab782..c178985 100644 --- a/design_pattern/singleton/static_local_singleton.cpp +++ b/design_pattern/singleton/static_local_singleton.cpp @@ -1,5 +1,7 @@ // // Created by light on 20-2-7. +// 在C++11标准下,《Effective C++》提出了一种更优雅的单例模式实现,使用函数内的 local static 对象。 +// 这种方法也被称为Meyers' Singleton。 // #include @@ -8,15 +10,14 @@ using namespace std; class singleton { private: - static singleton *p; singleton() {} public: - singleton *instance(); + static singleton &instance(); }; -singleton *singleton::instance() { +singleton &singleton::instance() { static singleton p; - return &p; + return p; }