utilities(C++)——单例(Singleton) (使用智能指针 shared_ptr)

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
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五道口纳什

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值