具有 访问修饰符 作为私有的被称为私有析构函数。无论何时,只要我们想防止破坏一个对象,我们就可以将析构函数设为私有。
私有析构函数有什么用?
每当我们想要控制类对象的销毁时,我们都会将析构函数设为私有。对于动态创建的对象,您可能会将指向该对象的指针传递给函数,而函数会删除该对象。如果在函数调用之后引用了对象,则引用将变为悬空。
预测以下程序的输出:
CPP
// CPP program to illustrate // Private Destructor #include <iostream> using namespace std; class Test { private : ~Test() {} }; int main() {} |
上述程序编译并运行良好。因此,我们可以说:是的 不 创建专用析构函数时出现编译器错误。
现在,你觉得下面的节目怎么样?
CPP
// CPP program to illustrate // Private Destructor #include <iostream> using namespace std; class Test { private : ~Test() {} }; int main() { Test t; } |
输出
prog.cpp: In function ‘int main()’: prog.cpp:8:5: error: ‘Test::~Test()’ is private ~Test() {} ^ prog.cpp:10:19: error: within this context int main() { Test t; }
上述程序编译失败。编译器注意到局部变量“t”不能被析构函数,因为析构函数是私有的。
下面的节目呢?
CPP
// CPP program to illustrate // Private Destructor #include <iostream> using namespace std; class Test { private : ~Test() {} }; int main() { Test* t; } |
以上程序运行良好。没有被构造的对象,程序只是创建一个类型为“Test*”的指针,所以没有任何东西被破坏。
接下来,下面的节目呢?
CPP
// CPP program to illustrate // Private Destructor #include <iostream> using namespace std; class Test { private : ~Test() {} }; int main() { Test* t = new Test; } |
上述程序也可以正常工作。当使用动态内存分配创建某个对象时,程序员有责任删除它。这样编译器就不用麻烦了。
在析构函数声明为private的情况下,还可以使用malloc()函数创建类的实例。 下面的程序也实现了同样的功能。
CPP
// CPP program to illustrate // Private Destructor #include <bits/stdc++.h> using namespace std; class Test { public : Test() // Constructor { cout << "Constructor called" ; } private : ~Test() // Private Destructor { cout << "Destructor called" ; } }; int main() { Test* t = (Test*) malloc ( sizeof (Test)); return 0; } |
上述程序也可以正常工作。然而,下面的程序编译失败。当我们调用delete时,就会调用析构函数。
CPP
// CPP program to illustrate // Private Destructor #include <iostream> using namespace std; class Test { private : ~Test() {} }; // Driver Code int main() { Test* t = new Test; delete t; } |
我们注意到,在上面的程序中,当一个类有一个私有析构函数时,只能创建该类的动态对象。下面是一个 使用私有析构函数创建类,并将其作为类的朋友。 该函数只能删除对象。
CPP
// CPP program to illustrate // Private Destructor #include <iostream> // A class with private destructor class Test { private : ~Test() {} public : friend void destructTest(Test*); }; // Only this function can destruct objects of Test void destructTest(Test* ptr) { delete ptr; } int main() { // create an object Test* ptr = new Test; // destruct the object destructTest(ptr); return 0; } |
必须阅读: C++中的构造函数是私有的吗?
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。