如何delete []知道要删除多少内存? [英] How does delete[] know how much memory to delete?

查看:214
本文介绍了如何delete []知道要删除多少内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int* i = new int[4];
delete[] i;




  1. 当我们调用delete []时,程序如何知道i 是4字节长度。

  2. 删除[]的实现取决于系统或编译器?

  3. 是否有某些系统API a的长度?

正如HadeS所说,这将保存已经分配了多少内存的信息?和在哪里?
它必须保存在内存中,或者可能在指针 i 附近。

As HadeS said, which will hold the information how much memory has been allocated? And where? It must be hold in memory, or maybe nearby the pointer i.

推荐答案

首先, i 不是4字节长度。相反, i 是指向四个int数组的指针。

First off, i is not "4-byte length". Rather, i is a pointer to an array of four ints.

接下来, delete [] 不需要知道任何东西,因为 int 没有析构函数。所有必须发生的是内存需要被释放,这是由系统的分配器。这是与 free(p)相同的情况 - 你不需要告诉 free 多少内存

Next, delete[] doesn't need to know anything, because int has no destructor. All that has to happen is that the memory needs to be freed, which is done by the system's allocator. This is the same situation as with free(p) -- you don't need to tell free how much memory needs to be freed, since you expect it to figure that out.

当需要调用析构函数时,情况有所不同。在这种情况下,C ++实现确实需要分别记住C ++对象的数量。此方法是由实现,虽然许多编译器遵循流行的 Itanium ABI ,允许将由这些不同编译器编译的对象代码链接在一起。

The situation is different when destructors need to be called; in that case, the C++ implementation does indeed need to remember the number of C++ objects separately. The method for this is up to the implementation, although many compilers follow the popular Itanium ABI, which allows linking together of object code compiled by those different compilers.

您无法查询此信息。你应该考虑动态数组是C ++的一个误区;基本上没有理由使用它们,你可以随时使用某种类别来管理内存和对象单独和单独:因为你必须记住数组元素的数量,所以最好封装大小和分配在一个连贯的类,而不是有模糊的动态数组,你不能真正使用,而无需传递额外的信息(除非你有自我终止的语义,但然后你只是使用额外的空间为终止符) 。

There is no way for you to query this information. You should consider dynamic arrays a misfeature of C++; there is essentially no reason to use them*, and you can always do better with some kind of class that manages memory and object separately and individually: Since you'll have to remember the number of array elements anyway, it's much better to encapsulate the size and the allocation in one coherent class, rather than have vague dynamic arrays that you cannot really use without passing extra information along anyway (unless you had self-terminating semantics, but then you'd just be using the extra space for the terminator).

*)动态数组至少有两个标准缺陷,没有人会担心修复

*) And there are at least two standard defects about dynamic arrays that nobody is too bothered to worry about fixing

这篇关于如何delete []知道要删除多少内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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