0

以下是否会正确销毁所有内容(调用所有适当的析构函数并释放所有内存)?

Class* var[50];
var[0] = new SubClass();

delete[] *var;

如同

Class** var = new Class*[50];
var[0] = new SubClass();

delete[] var;

或者我应该遍历数组并删除每个单独的对象(这是我认为 delete[] 所做的)。

4

4 回答 4

3

正确的方法是使用像std::vector<std::unique_ptr<MyClass>>. 这将始终保证正确的资源清理,无需用户干预。任何看到或使用的 C++ 代码都delete应该new[]立即delete[]重构以避免它们——并且new应该再看一遍。

于 2012-04-18T21:30:44.850 回答
0
Class* var[50];
var[0] = new SubClass();

delete[] *var;

This is undefined behavior. The proper way is

delete var[0]; //equivalent to delete *var;

If you allocate memory for all 50 elements of the array, then you have to iterate and delete each one of them. Think of it this way:

  • for every new, you should have an associated delete
  • for every new[], you should have an associate delete[]
  • don't mix up new with delete[] and new[] with delete as it leads to undefined behavior

Your second snippet is illegal C++.

EDIT As you're clearly a beginner, let's break this down a bit. Since the second snippet doesn't even compile, I'm going to focus on the first one:

Class* var[50];

This declares an array of 50 pointers to Class. The pointers are dangling - they are not initialized and Class objects aren't created.

var[0] = new SubClass();

This allocates memory for a SubClass object and assigns the first pointer in the array. All other pointers remain uninitialized.

*var;

returns the first element, which is a Class*. It's equivalent to var[0].

delete[] *var;

attempts to call delete[] on a Class*, which was allocated with new, so it results in undefined behavior.

于 2012-04-18T21:21:46.693 回答
0

delete[]用于动态分配的数组。它对应于new []

摘自 C++ 开放标准 (3.7.4.2)

如果释放函数因抛出异常而终止,则行为未定义。提供给释放函数的第一个参数的值可以是空指针值;如果是这样,并且如果释放函数是标准库中提供的函数,则调用无效。否则,标准库中提供给 operator delete(void*)的值应是先前调用 operator new(std::size_t) 或 operator new(std::size_t, const std::时返回的值之一nothrow_t&) 在标准库中,提供给标准库中 operator delete[](void*)的值应是先前调用任一 operator new[](std::size_t)返回的值之一或标准库中的 operator new[](std::size_t, const std::nothrow_t&) 。

你的第一个例子不使用new []所以你不应该使用delete []!!!

于 2012-04-18T21:28:13.293 回答
-2
for(int i = 0; i < 50;i++)delete var[i];
delete[] var;
于 2012-04-18T21:21:33.923 回答