删除和删除[]删除数组时是否相同? [英] Delete and delete [] are the same when deleting arrays?
问题描述
可能的重复项:
如何将new []与delete配对可能会导致内存泄漏?
(POD)释放内存:是delete []等于删除吗?
使用gcc版本4.1.2 20080704(Red Hat 4.1.2-48)。没有在Visual C ++上测试它。
Using gcc version 4.1.2 20080704 (Red Hat 4.1.2-48). Haven't tested it on Visual C++.
似乎 delete
和 delete []
删除简单类型的数组时也是如此。
It seems that delete
and delete []
works the same when deleting arrays of "simple" type.
char * a = new char[1024];
delete [] a; // the correct way. no memory leak.
char * a = new char[1024];
delete a; // the incorrect way. also NO memory leak.
But, when deleting arrays of "complex" type, delete
will cause memory leak.
class A
{
public:
int m1;
int* m2; // a pointer!
A()
{
m2 = new int[1024];
}
~A()
{
delete [] m2; // destructor won't be called when using delete
}
};
A* a = new A[1024];
delete [] a; // the correct way. no memory leak.
A* a = new A[1024];
delete a; // the incorrect way. MEMORY LEAK!!!
我的问题是:
- 在第一个测试用例中,为什么
delete
和delete []
/ li>
- 在第二个测试用例中,为什么g ++不像第一个测试用例那样处理它呢?
- In the first test case, why
delete
anddelete []
are the same under g++? - In the second test case, why g++ doesn't handle it like the first test case?
推荐答案
这完全取决于底层的内存管理器。简单来说,C ++要求您使用 delete []
删除数组,并使用 delete
删除非数组。
This is all dependent on the underlying memory manager. Simply put, C++ requires that you delete arrays with delete[]
and delete non-arrays with delete
. There is no explanation in the standard for your behaviour.
然而,可能发生的是 delete p;
从 p
开始的内存块(无论是否为数组)。另一方面, delete []
另外运行数组的每个元素,并调用析构函数。由于 char
的正常数据类型没有析构函数,因此没有效果,因此 delete
和 delete []
最后做同样的事情。
What's likely happening however is that delete p;
simply frees the block of memory starting at p
(whether it is an array or not). On the other hand delete[]
additionally runs through each element of the array and calls the destructor. Since normal data types like char
don't have destructors, there is no effect, so delete
and delete[]
end up doing the same thing.
就像我说的,不能保证 delete
将适用于任何类型的数组。它只是碰巧在你的情况下工作。在C ++中,我们称之为未定义的行为 - 它可能工作,它可能不会,它可能做一些完全随机和意想不到的事情。你最好避免依赖未定义的行为。
Like I said, this is all implementation specific. There's no guarantee that delete
will work on arrays of any type. It just happens to work in your case. In C++ we call this undefined behaviour -- it might work, it might not, it might do something totally random and unexpected. You'd be best to avoid relying on undefined behaviour.
这篇关于删除和删除[]删除数组时是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!