Quantcast
Channel: C++博客-所有随笔
Viewing all articles
Browse latest Browse all 7881

智能指针单例

$
0
0
智能指针单例

(金庆的专栏)

普通单例如果是new出来的,一般不会有删除,或者需要调用一个删除函数;
如果是static,将会在main()之后删除,无法做到在main()结束时删除.

智能指针的单例,在初次使用时new, 当无人引用时自动删除,删除后还会new.

原理是保存一个weak_ptr, 返回智能指针.

 1 class SmartSingleton : boost::noncopyable
 2 {
 3 private:
 4     static boost::mutex _mutex;
 5     static boost::weak_ptr<SmartSingleton> _thisWeakPtr;
 6 
 7     SmartSingleton();
 8 
 9 public:
10     ~SmartSingleton();
11 
12     typedef boost::shared_ptr<SmartSingleton> SmartSingletonPtr;
13     static SmartSingletonPtr getInstance()
14     {
15         SmartSingletonPtr p = _thisWeakPtr.lock();
16         if (p) return p;
17         boost::lock_guard<boost::mutex> lock(_mutex);
18         p = _thisWeakPtr.lock();
19         if (p) return p;
20         p.reset(new SmartSingleton);
21         _thisWeakPtr = p;
22         return p;
23     }
24 };
25 
26 boost::weak_ptr<SmartSingleton> SmartSingleton::_thisWeakPtr;
27 boost::mutex SmartSingleton::_mutex;
28 

参考:

(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/


金庆 2014-02-02 14:44 发表评论

Viewing all articles
Browse latest Browse all 7881

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>