智能指標單例

來源:互聯網
上載者:User

智能指標單例

(金慶的專欄)

普通單例如果是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/


修正: 可能需要在析構時禁止產生新的執行個體.


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.