智能指標單例
(金慶的專欄)
普通單例如果是new出來的,一般不會有刪除,或者需要調用一個刪除函數;
如果是static,將會在main()之後刪除,無法做到在main()結束時刪除.
智能指標的單例,在初次使用時new, 當無人引用時自動刪除,刪除後還會new.
原理是儲存一個weak_ptr, 返回智能指標.
class SmartSingleton : boost::noncopyable{private: static boost::mutex _mutex; static boost::weak_ptr<SmartSingleton> _thisWeakPtr; SmartSingleton();public: ~SmartSingleton(); typedef boost::shared_ptr<SmartSingleton> SmartSingletonPtr; static SmartSingletonPtr getInstance() { SmartSingletonPtr p = _thisWeakPtr.lock(); if (p) return p; boost::lock_guard<boost::mutex> lock(_mutex); p = _thisWeakPtr.lock(); if (p) return p; p.reset(new SmartSingleton); _thisWeakPtr = p; return p; }};boost::weak_ptr<SmartSingleton> SmartSingleton::_thisWeakPtr;boost::mutex SmartSingleton::_mutex;
參考:
(A dynamic) Singleton using weak_ptr and shared_ptr
http://boost.2283326.n4.nabble.com/A-dynamic-Singleton-using-weak-ptr-and-shared-ptr-td2581447.html
Several C++ singleton implementations
http://silviuardelean.ro/2012/06/05/few-singleton-approaches/
修正: 可能需要在析構時禁止產生新的執行個體.