C++ new int[0]——它会分配内存吗?
一个简单的测试应用程序:
cout << new int[0] << endl;
输出:
0x876c0b8
所以看起来它可以工作。 标准对此有何规定? “分配”空内存块总是合法的吗?
A simple test app:
cout << new int[0] << endl;
outputs:
0x876c0b8
So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从5.3.4/7
从3.7.3.1/2开始
还
这意味着您可以做到这一点,但您不能合法地(在所有平台上以明确定义的方式)取消引用您获得的内存 - 您只能将其传递给数组删除 - 并且您应该删除它。
这是一个有趣的脚注(即不是标准的规范部分,但出于解释目的而包含在内),附在 3.7.3.1/2 的句子中
From 5.3.4/7
From 3.7.3.1/2
Also
That means you can do it, but you can not legally (in a well defined manner across all platforms) dereference the memory that you get - you can only pass it to array delete - and you should delete it.
Here is an interesting foot-note (i.e not a normative part of the standard, but included for expository purposes) attached to the sentence from 3.7.3.1/2
是的,像这样分配一个零大小的数组是合法的。 但您也必须将其删除。
Yes, it is legal to allocate a zero-sized array like this. But you must also delete it.
每个对象都有一个唯一的标识,即唯一的地址,这意味着非零长度(如果您要求零字节,则实际的内存量将悄悄增加)。
如果您分配了多个这些对象,那么您会发现它们具有不同的地址。
Every object has a unique identity, i.e. a unique address, which implies a non-zero length (the actual amount of memory will be silently increased, if you ask for zero bytes).
If you allocated more than one of these objects then you'd find they have different addresses.
是的,使用
new
分配0
大小的块是完全合法的。 您根本无法用它做任何有用的事情,因为没有可供您访问的有效数据。int[0] = 5;
是非法的。但是,我相信该标准允许诸如
malloc(0)
之类的东西返回NULL
。您仍然需要
删除[]
从分配中返回的任何指针。Yes it is completely legal to allocate a
0
sized block withnew
. You simply can't do anything useful with it since there is no valid data for you to access.int[0] = 5;
is illegal.However, I believe that the standard allows for things like
malloc(0)
to returnNULL
.You will still need to
delete []
whatever pointer you get back from the allocation as well.我向你保证 new int[0] 会花费你额外的空间,因为我已经测试过它。
例如,
的内存使用量
明显小于
第二个代码段的内存使用量减去第一个代码段的内存使用量就是无数个new int[0]所使用的内存。
I guarantee you that new int[0] costs you extra space since I have tested it.
For example,
the memory usage of
is significantly smaller than
The memory usage of the second code snippet minus that of the first code snippet is the memory used for the numerous new int[0].
我发现Effective C++ Third Edition在“Item 51:编写new和delete时遵守约定”中这样说。
I found Effective C++ Third Edition said like this in "Item 51: Adhere to convention when writing new and delete".