gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:48:28 24 4
gpt4 key购买 nike

一个简单的测试应用:

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.

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

这是一个有趣的脚注(即不是标准的规范部分,但出于说明目的)附在 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/33650710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com