utilities(C++)——单例(Singleton) (使用智能指针 shared_ptr)
来源:互联网 发布:深圳壹基金知乎 编辑:程序博客网 时间:2024/06/06 20:31
utilities(C++)——单例(Singleton)
上文简单版的单例类的实现的一大核心问题,在于new
出来的堆对象不会被释放,就有可能造成内存泄漏的风险。
class Singleton{public: // 通过类名获得类实例指针 static Singleton* instance() { if (!_instance) _instance = new Singleton; return _instance; } ~Singleton() { std::cout << "Singleton::~Singleton()" << std::endl; }private: // 禁止拷贝 Singleton(const Singleton& ); Singleton& operator=(const Singleton& ); // 将构造函数声明为私有的 Singleton() { std::cout <<"Singleton::Singleton()" << std::endl; } static Singleton* _instance;};Singleton* Singleton::_instance = NULL;int main(int, char**){ Singleton* s1 = Singleton::instance(); Singleton* s2 = Singleton::instance(); // 只会调用其构造函数 // 而不会调用其析构函数 return 0;}
法一
我们可在单例类内部给出一个 destroy 函数用于对 new 出来的对象进行析构,然后在客户端显式地进行调用。
void destroy(){ delete _instance; _instance = 0;}
法二
智能指针是进行内存管理的重要工具。我们就以智能指针对类实例指针进行封装,已达到释放堆内存的作用。
#include <iostream>#include <boost\shared_ptr.hpp>class Singleton{public: static boost::shared_ptr<Singleton> instance() { if (_instance == 0) _instance = boost::shared_ptr<Singleton>(new Singleton); return _instance; } ~Singleton() { std::cout << "Singleton::~Singleton()" << std::endl; }private: Singleton(const Singleton&); Singleton() { std::cout << "Singleton::Singleton()" << std::endl; } Singleton& operator=(const Singleton&); static boost::shared_ptr<Singleton> _instance;};boost::shared_ptr<Singleton> Singleton::_instance = NULL;int main(int, char**){ boost::shared_ptr<Singleton> s = Singleton::instance(); boost::shared_ptr<Singleton> s2 = Singleton::instance(); return 0;}
0 0
- utilities(C++)——单例(Singleton) (使用智能指针 shared_ptr)
- utilities(C++)——单例(Singleton)
- 【C++】智能指针shared_ptr 定位删除器(仿函数)
- C++11智能指针之shared_ptr的使用(1)
- C++ TR1 智能指针shared_ptr的使用(转)
- 有关智能指针(shared_ptr)的讨论
- 智能指针(四)之shared_ptr
- Boost智能指针—shared_ptr
- utilities(C/C++)
- utilities(C++)——枚举
- utilities(C++)——错误提示
- utilities(C++)——宏函数
- C/C++ 日常学习总结(第二十一篇)智能指针shared_ptr
- C++:智能指针之shared_ptr
- 智能指针tr1::shared_ptr、boost::shared_ptr使用
- c++智能指针(三)之shared_ptr和new结合使用
- Boost智能指针——shared_ptr
- [转载]Boost智能指针——shared_ptr
- .NET简谈事务、分布式事务处理
- 【android】怎么压缩和缓存图片?告诉你正确的姿势
- oracle 使用触发器更新插入列的id
- TCP提供可靠传输的工作原理和实现过程
- windows socket 编程
- utilities(C++)——单例(Singleton) (使用智能指针 shared_ptr)
- 操作系统可变分区用C语言实现按最佳适应算法分配内存
- Android查找方法所在的包快捷键
- Android获取SD卡上所有图片、视频缩略图和音乐专辑封面
- 第三周项目-委派任务
- Android 自定义滑动容器View(2)
- ubuntu操作系统安装(二) curses
- http://zh.visualgo.net/mst.html
- perl 实现微信简版<2>