析构函数和函数之间的区别是什么?
问题描述:
这段代码中的析构函数和DeAllocate函数有什么区别?析构函数和函数之间的区别是什么?
我不明白它们对我来说看起来像是一样的东西。它们完全一样,为什么你需要像DeAllocate这样的函数?析构函数具有自动调用的好处,但DeAllocate不会。
#include <iostream>
using namespace std;
const int SIZE=5;
class ARRAY_CLASS
{
public:
ARRAY_CLASS();//default constructor
~ARRAY_CLASS(); //destructor
void Add(int); //mutator
void Print(); //accessor
int * Get_Address(); //accessor
void DeAllocate(); //mutator
private:
int *A;
int count;
};
ARRAY_CLASS::ARRAY_CLASS()
{
cout<<"Default constructor has been called\n";
A = new int[SIZE];
count = 0;
}
ARRAY_CLASS::~ARRAY_CLASS()
{
cout<<"The Destructor has been Called!\n";
delete [ ] A;
A=0;
count = 0;
}
void ARRAY_CLASS::Add(int item)
{
if (count<SIZE)
A[count++]=item;
else
cout<<"Array Full\n";
}
void ARRAY_CLASS::Print()
{
for(int i=0; i<count; i++)
cout<<"A[i] = "<<A[i]<<endl;
}
int * ARRAY_CLASS::Get_Address()
{
return A;
}
void ARRAY_CLASS::DeAllocate()
{
delete [ ] A;
A = 0;
count = 0;
}
int main()
{
ARRAY_CLASS B;
B.Add(1);
B.Add(2);
B.Add(3);
B.Add(4);
B.Add(5);
B.Print();
ARRAY_CLASS A = B;
cout<<"A holds address location = "<<A.Get_Address()
<<" and B holds address location "<<B.Get_Address()<<endl;
B.DeAllocate();
A.Print();
return 0;
}
答
人们可能确实改写了析构函数:
ARRAY_CLASS::~ARRAY_CLASS()
{
cout<<"The Destructor has been Called!\n";
DeAllocate();
}
的不同之处在于:
析构函数离开范围时,在销毁调用(自动为本地对象,其中,对象被创建,或者当对象被删除以获得freestore对象时)。对象被销毁后,该对象不再存在。
当您调用
DeAllocate();
时,数组的内存被释放并且对象的状态发生变化,但其所有成员和ARRAY_CLASS对象本身仍然存在。
*析构函数具有自动调用的好处,但DeAllocate不会。*就是这样。认真。除此之外,再看看。 RAII依赖于此。在大多数语言中都存在相同的概念,甚至是托管的概念(例如,在C#中将'IDisposable'与'using'结合起来使用)。这使我们的日常生活变得更好。 –
偏题:强烈推荐'A = nullptr;'over'A = 0;'。第一个意图对于不经意的读者来说更为明显。 – user4581301
'DeAllocate()'方法在这里可能不应该存在。它使对象处于无效状态。应该只有一个析构函数。 – EJP