删除指针成员变量的数组内存

Deleting array memory for a pointer member variable

我在看一本教科书,好像说当你有一个成员变量是指针时,你必须把代码放在析构函数中才能删除内存。
有点不清楚,但似乎代码必须如下所示:

private:  
double *aPtr;

public:  
~NumberArray(){ delete [ ] aPtr;}

不过,这不会是 2 个删除命令吗,因为析构函数已经删除了该数组中的第一个元素?此外,析构函数是否会自动执行其默认工作,即使您的程序中有 1 行或多行用于默认析构函数?程序是先执行您的代码,还是先执行析构函数的 "automatic" 部分的代码?

出于某种原因,我认为删除命令仅用于动态分配的内存。我想我错了?

Doesn't this end up being 2 delete commands, though, because the destructor is already deleting the first element in that array?

析构函数正在析构 指针(这是一个空操作)。但它根本没有触及指针指向的内容。所以没有任何删除操作,除非你自己明确地写一个。

Also, do destructors automatically do their default work, even if you have 1 or more lines in your program for the default destructor?

是的,析构函数总是会销毁对象的成员和基类(在执行析构函数体之后)。但同样,该成员是 aPtr。这不是 aPtr 指向的任何东西。

Does the program execute your code first or it executes the code the "automatic" part of the destructor?

对象的任何成员在析构函数体期间仍然存在。这是有道理的,因为清理相关操作可能需要它们。在那之后,他们确实被摧毁了。

您似乎对 deletedelete[] 之间的区别感到困惑。

delete的第一种形式(没有括号),用于销毁为单个对象分配的动态内存。这种形式不应用于数组,因为在这种情况下,编译器将只调用一次析构函数。

第二种形式,带方括号,保证在释放数组使用的内存之前,为动态分配数组的每个元素调用析构函数。

简而言之:

// first form:
SomeClass* object = new SomeClass;
delete object;                     // SomeClass::~SomeClass is called once, which is good.

// second form
SomeClass* array = new SomeClass[N]; // SomeClass::SomeClass() is called N times.
delete[] array;      // SomeClass::~SomeClass is called N times, which is good.
delete array;        // YIKES!! SomeClass::~SomeClass is called only once. 
                     // This is terrible, as N-1 destructors did not get called.