删除和删除[]删除数组时是否相同? [英] Delete and delete [] are the same when deleting arrays?

查看:123
本文介绍了删除和删除[]删除数组时是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项

如何将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!!!

我的问题是:


  1. 在第一个测试用例中,为什么 delete delete [] / li>
  2. 在第二个测试用例中,为什么g ++不像第一个测试用例那样处理它呢?

  1. In the first test case, why delete and delete [] are the same under g++?
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆