utilities(C++)——单例(Singleton) (使用智能指针 shared_ptr)
2016-03-13 16:16
519 查看
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; }
相关文章推荐
- C++ decltype类型说明符
- 逗号运算符与加加减减
- C和C++ const的声明差异
- 浅谈C++内联函数
- C++ decltype类型说明符
- C++ decltype类型说明符
- Cygwin下 vim编写 C / C++
- C++ auto类型说明符
- utilities(C++)——单例(Singleton)
- c++实现线程池
- C++基础::构造函数
- c++ 小知识点
- lesson 01 Hello Sdl
- c++的上机作业2
- c++上机作业1
- ROS基础学习笔记——工作空间、CMakeList、package.xml
- C++命名空间详解std
- Simplified Memory Modle C/C++内存模型
- c++ binarytree(二叉树)
- 类String的构造函数、析构函数和赋值函数