智能指针单例
2014-02-02 14:39
816 查看
智能指针单例
(金庆的专栏)
普通单例如果是new出来的,一般不会有删除,或者需要调用一个删除函数;
如果是static,将会在main()之后删除,无法做到在main()结束时删除.
智能指针的单例,在初次使用时new, 当无人引用时自动删除,删除后还会new.
原理是保存一个weak_ptr, 返回智能指针.
参考:
(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/
修正: 可能需要在析构时禁止产生新的实例.
(金庆的专栏)
普通单例如果是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/
修正: 可能需要在析构时禁止产生新的实例.
相关文章推荐
- 【17】以独立语句将newed对象置入智能指针
- 科锐课堂笔记:2017/4/21 多重继承与智能指针
- 【C++】智能指针auto_ptr简单的实现
- RPCZ中的智能指针单例
- c++智能指针
- 智能指针
- 引用内部函数绑定机制,R转义字符,C++引用,别名,模板元,宏,断言,C++多线程,C++智能指针
- auto_ptr智能指针不能作为STL标准容器的元素
- Hat’s Words (字典树 + 智能指针shared_ptr)
- 智能指针(auto_ptr 和 shared_ptr)
- C++ string 类 部分成员函数实现(实现COW copy-on-write+实现智能指针(有极大bug版本))
- 什么是智能指针
- 【C++】智能指针
- cpp的智能指针
- Android系统的智能指针(轻量级指针、强指针和弱指针)的实现原理分析
- 智能指针(OSG源码摘录)
- C++11 FAQ中文版:共享资源的智能指针——shared_ptr
- C++ 智能指针详解
- 智能指针学习
- C++利用智能指针桥接模式设计