一个简单的测试应用:
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/