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

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

#include
#include
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;
}

C++单例模式下无法执行析构函数的分析过程_第1张图片

你可能感兴趣的:(C++,c++)