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

标签 c++ memory-management new-operator standards-compliance

一个简单的测试应用:

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

输出:

0x876c0b8

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

最佳答案

从 5.3.4/7 开始

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 开始

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

还有

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

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

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

[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]——它会分配内存吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1087042/

相关文章:

swift - 使用 Apple Instruments 进行高内存分配调试

c++ - 在不分配内存的情况下使用 placement new 是否安全?

c++ - VisualStudio - 非常长的监视变量的别名

c++ - 如何加快这个素数测试

linux - 在 Linux 上限制进程内存/CPU 使用

c++ - new 和 new[1] 有什么区别?

c++ - GCC malloc()这是正确的吗?

c++ - 返回在堆上分配的类的实例 (C++)

c# - 在 Windows 7 中分析文件的碎片

ios - 使用 AFNetworking 下载文件时出现内存警告