问题描述
是很难用一个关键字来实现阵列的缺失?它是低效率的?
Is it hard to implement deletion of array using a single keyword? Is it less efficient?
推荐答案
首先,让我总结一下都这样做:删除
调用析构函数的有一个对象并释放内存; 删除[]
调用析构函数的部分的对象的数目,并释放内存。
First, let me summarize what both do: delete
calls a destructor for one object and deallocates the memory; delete[]
calls the destructor of some number of objects and deallocates the memory.
一个可以折叠到这些相同的操作:要求的的某些对象的数量并释放内存中的析构函数。毕竟有一个的是部分的数量。
One could fold these into the same operation: "calls the destructor of some number of objects and deallocates the memory.". After all one is some number.
两者删除
和删除[]
上的指针操作。像这样的:
Both delete
and delete[]
operate on a pointer. Like this one:
foo* ptr;
仔细看看它。并告诉了我很多的析构函数应该怎么叫,当我们删除
它。你不能。所以不能编译。这只能在运行时是已知的。约的对象的数目的信息具有要被存储的某处的。这意味着,对于每次使用新[]
,有分配给跟踪这个数字的一些额外的内存。
Look at it closely. And tell me how many destructors should be called when we delete
it. You can't. And so can't the compiler. This can only be known at runtime. The information about the number of objects has to be stored somewhere. That means that, for each usage of new[]
, there is some extra memory allocated to keep track of that number.
C ++是建立在你不支付你没有用什么的原则,这就是为什么非数组形式存在:因为删除
永远只删除一个对象,新
不需要分配任何额外的。
C++ is built on the principle of "you don't pay for what you don't use", and that's why the non-array forms exist: since delete
always only deletes one object, new
doesn't need to allocate any extra.
这篇关于为什么C ++仍然有删除[]和delete运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!