首先我们来看一下下面这个程序的输出:
#include <iostream>using namespace std;class Test {private:~Test() {}};int main(){}
上面的程序可以编译并正常运行。因此,我们可以说:不是创建私有析构函数编译器错误。
现在,您对下面的程序怎么说?
#include <iostream>using namespace std;class Test {private:~Test() {}};int main(){Test t;}
上面的程序编译失败。编译器注意到,因为析构函数是私有的,所以无法破坏局部变量“ t”。
现在,下面的程序呢?
#include <iostream>using namespace std;class Test {private:~Test() {}};int main(){Test* t;}
上面的程序工作正常。没有正在构造的对象,程序仅创建“ Test *”类型的指针,因此不会破坏任何内容。
接下来,下面的程序呢?
#include <iostream>using namespace std;class Test {private:~Test() {}};int main(){Test* t = new Test;}
上面的程序也可以正常工作。当使用动态内存分配创建某些内容时,程序员有责任将其删除。因此,编译器不会打扰。
**在将析构函数声明为私有的情况下,也可以使用malloc()函数创建该类的实例。**在下面的程序中实现相同。
#include <bits/stdc++.h>using namespace std;class Test {public:Test() // Constructor{cout << "Constructor called\n";}private:~Test() // Private Destructor{cout << "Destructor called\n";}};int main(){Test* t = (Test*)malloc(sizeof(Test));return 0;}
但是,以下程序编译失败。当我们调用delete时,将调用析构函数。
#include <iostream>using namespace std;class Test {private:~Test() {}};int main(){Test* t = new Test;delete t;}
我们在上面的程序中注意到,当一个类具有私有析构函数时,只能创建该类的动态对象。以下是一种**使用私有析构函数创建类并具有作为类朋友的功能的方法。**该功能只能删除对象。
#include <iostream>// A class with private destuctorclass Test {private:~Test() {}friend void destructTest(Test*);};// Only this function can destruct objects of Testvoid destructTest(Test* ptr){delete ptr;}int main(){// create an objectTest* ptr = new Test;// destruct the objectdestructTest(ptr);return 0;}
私有析构函数的用途是什么?
每当我们想要控制类对象的销毁时,我们都将析构函数设为私有。对于动态创建的对象,可能会发生以下情况:将指向该对象的指针传递给函数,然后该函数删除该对象。如果在函数调用后引用了对象,则该引用将变得悬而未决。
以上就是今天的全部内容了。每日分享小知识,希望对你有帮助~
**另外如果你想更好的提升你的编程能力,学好C语言C++编程!**弯道超车,快人一步!笔者这里或许可以帮到你~
C语言C++编程学习交流圈子,**QQ群【951258402】**微信公众号:C语言编程学习基地
分享(源码、项目实战视频、项目笔记,基础入门教程)
欢迎转行和学习编程的伙伴,利用更多的资料学习成长比自己琢磨更快哦!
编程学习视频分享: