C++中的析构函数可以私有吗?私有析构函数如何使用?

2021年3月19日12:56:59 发表评论 606 次浏览

另请阅读:

C++的构造函数可以私有吗?

预测以下程序的输出。

// CPP program to illustrate 
// Private Destructor
#include <iostream>
using namespace std;
  
class Test {
private :
     ~Test() {}
};
int main()
{
}

上面的程序可以编译并正常运行。因此, 我们可以这样说:不创建私有析构函数时发生编译器错误。

现在, 你对下面的程序怎么说?

// CPP program to illustrate 
// Private Destructor
#include <iostream>
using namespace std;
  
class Test {
private :
     ~Test() {}
};
int main()
{
     Test t;
}

上面的程序编译失败。编译器注意到, 因为析构函数是私有的, 所以无法破坏局部变量" t"。

现在, 下面的程序呢?

// CPP program to illustrate 
// Private Destructor
#include <iostream>
using namespace std;
  
class Test {
private :
     ~Test() {}
};
int main()
{
     Test* t;
}

上面的程序工作正常。没有正在构造的对象, 程序仅创建" Test *"类型的指针, 因此不会破坏任何内容。

接下来, 下面的程序呢?

// CPP program to illustrate 
// Private Destructor
  
#include <iostream>
using namespace std;
  
class Test {
private :
     ~Test() {}
};
int main()
{
     Test* t = new Test;
}

上面的程序也可以正常工作。使用动态内存分配创建某些内容时, 程序员有责任将其删除。因此, 编译器不会打扰。

在将析构函数声明为私有的情况下, 也可以使用malloc()函数创建该类的实例。在下面的程序中实现相同。

// CPP program to illustrate 
// Private Destructor 
  
#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时, 将调用析构函数。

// CPP program to illustrate 
// Private Destructor
#include <iostream>
using namespace std;
  
class Test {
private :
     ~Test() {}
};
int main()
{
     Test* t = new Test;
     delete t;
}

我们在上面的程序中注意到, 当一个类具有私有的析构函数时, 只能创建该类的动态对象。以下是一种方法创建带有私有析构函数的类, 并具有作为该类的朋友的功能。该功能只能删除对象。

// CPP program to illustrate 
// Private Destructor
#include <iostream>
  
// A class with private destuctor
class Test {
private :
     ~Test() {}
     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;
}

私有析构函数的用途是什么?

每当我们想要控制类对象的销毁时, 我们都将析构函数设为私有。对于动态创建的对象, 可能会发生以下情况:将指向该对象的指针传递给函数, 然后该函数删除该对象。如果在函数调用后引用了对象, 则该引用将变得悬而未决。看到这个更多细节。

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请发表评论。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: