C++ new int[0] -- 会分配内存吗?

C++ new int[0] -- will it allocate memory?(C++ new int[0] -- 会分配内存吗?)
本文介绍了C++ new int[0] -- 会分配内存吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的测试应用:

cout << new int[0] << endl;

输出:

0x876c0b8

所以看起来它有效.标准对此有何评论?分配"空内存块总是合法的吗?

So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?

推荐答案

来自 5.3.4/7

当 direct-new-declarator 中表达式的值为零时,调用分配函数来分配一个没有元素的数组.

When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

来自 3.7.3.1/2

From 3.7.3.1/2

取消引用作为零大小请求返回的指针的效果未定义.

The effect of dereferencing a pointer returned as a request for zero size is undefined.

还有

即使 [by new] 请求的空间大小为零,请求也可能失败.

Even if the size of the space requested [by new] is zero, the request can fail.

这意味着您可以这样做,但您不能合法地(在所有平台上以明确定义的方式)取消引用您获得的内存 - 您只能将其传递给数组删除 - 您应该删除它.

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.

这是一个有趣的脚注(即不是标准的规范部分,但包含在说明中)附在 3.7.3.1/2 的句子中

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

[32.目的是通过调用 malloc() 或 calloc() 来实现 operator new(),因此规则基本相同.C++ 与 C 的不同之处在于要求零请求返回非空指针.]

[32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.]

这篇关于C++ new int[0] -- 会分配内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)