智能指针单例
(金庆的专栏)
普通单例如果是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/
修正: 可能需要在析构时禁止产生新的实例.