C++单例模式下无法执行析构函数的分析过程

==单例模式下的带有指针的成员static A instance_无法直接析构的,如果手动调用析构会出现无限递归调用析构函数~A(),因此需要采用一点技巧:内置一个类:deleteClassA,在deleteClassA析构函数中释放static A instance,并声明一个静态成员变量static deleteClassA deleteClassA_,这种做法可以保证无内存泄漏的风险==**

#include<iostream>
#include<assert.h>
using namespace std;
class A{
public:
    static A* getInstance();
    A(const A& other) = delete;
    class deleteClassA
	{
	public:
        deleteClassA(){
            cout<<"deleteClassA construct"<<endl;
        }
		~deleteClassA() {
			if (A::instance_)
			{
                cout<<"delete Class A"<<endl;
				delete A::instance_;
				A::instance_ = nullptr;
			}
		}
	};
    static deleteClassA deleteClassA_;
private:
    static A* instance_;
    A(){
        cout<<"A construct and instance_ addr:"<<instance_<<endl;
    }
};
A::deleteClassA A::deleteClassA_;
A* A::instance_;
A* A::getInstance(){
        if(instance_ == nullptr){
            instance_ = new A;
            return instance_;
        }
        return instance_;
}

class B{
public:
    static B& getInstance();
    B(const B& other) = delete;
    B& operator =(const operator&) = delete;
private:
    static B instance;
    B(){
        cout<<"B construct"<<endl;
    }
    ~B(){
        cout<<"~B"<<endl;
    }
};
B B::instance;
B& B::getInstance(){
    return instance;
}
int* testPoint(){
    int* p = new int(10);
    cout<<"p addr"<<p<<endl;
    return p;
}
A* testClassPointer(){
    A* a1 = A::getInstance();
    return a1;
}
 void testClassPointer1(){
     B& b1 = B::getInstance();
     B& b2 = B::getInstance();
 }
int main(){
     A* a1 = A::getInstance();
     A* a2 = A::getInstance();
     assert(a1 == a2);
     A* a = testClassPointer();
    if(a != nullptr){
        cout<<"a addr is not nullptr:"<<a<<endl;
    } else{
        cout<<"a addr is nullptr"<<endl;
    }
    return 0;
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Alex1_Code

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

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

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

打赏作者

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

抵扣说明:

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

余额充值