您的位置:首页 > 编程语言 > C语言/C++

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: