C ++ new int [0] - 它会分配内存吗? [英] C++ new int[0] -- will it allocate memory?

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

问题描述

一个简单的测试应用程式:

A simple test app:

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

输出:

0x876c0b8

标准是什么说的?

推荐答案

从5.3.4 / 7

From 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。目的是让操作符new()可以通过调用malloc()或calloc()实现,所以规则基本上是相同的。 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] - 它会分配内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆