智能指针单例


智能指针单例

(金庆的专栏)

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


修正: 可能需要在析构时禁止产生新的实例.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值