58 单例模式与auto_ptr

本文详细介绍了如何通过智能指针管理来确保单例模式中析构函数的正确调用,避免了资源泄漏的问题。通过实例演示了在C++中实现这一优化的过程,包括初始化和析构过程的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用智能指针管理,可以使单例模式调用析构函数

#include <iostream>
#include <memory>
using namespace std;

class Singleton
{
public:
    static Singleton* GetInstance()
    {
        /*if (instacne_ == NULL)
        {
            instacne_ = new Singleton;
        }
        return instacne_;*/
        if (!instance_.get())//获得裸指针
        {
            instance_ = auto_ptr<Singleton>(new Singleton);
        }

        return instance_.get();//返回原生指针,但是还保留所有权
    }

    ~Singleton()
    {
        cout<<"~Singleton ..."<<endl;
    }
private:
    Singleton(const Singleton& other);//禁止拷贝
    Singleton& operator=(const Singleton& other);
    //将构造函数声明为私有
    Singleton()
    {
        cout<<"Singleton ..."<<endl;
    }
    static auto_ptr<Singleton> instance_;
};

auto_ptr<Singleton> Singleton::instance_;

int main(void)
{
    //Singleton s1;
    //Singleton s2;

    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();

    //Singleton s3(*s1);        // 调用拷贝构造函数

    return 0;
}
#include<iostream>
using namespace std;

//两指针相减,得到的是相隔几个元素
#define sizeof_v(x) (char*)(&x+1) -(char*)(&x)

#define sizeof_t(t) ((size_t)((t*)0+1))

//对齐
#define ALIGN(v,b) ((v+b-1) & ~(b-1))
class Empty
{


};

int main(void)
{
    Empty e;
    int n;
    cout << sizeof_v(n) << endl;
    cout << sizeof_t(Empty) << endl;

    cout << ALIGN(3, 16) << endl;
    cout << ALIGN(31, 16) << endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值