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

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

问题描述

A simple test app:

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

outputs:

0x876c0b8

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

解决方案

From 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.

From 3.7.3.1/2

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

Also

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.

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. 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]——它会分配内存吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

What are access specifiers? Should I inherit with private, protected or public?(什么是访问说明符?我应该以私有、受保护还是公共继承?)
What does extern inline do?(外部内联做什么?)
Why can I use auto on a private type?(为什么我可以在私有类型上使用 auto ?)
Why cast unused return values to void?(为什么将未使用的返回值强制转换为 void?)
How to implement big int in C++(如何在 C++ 中实现大 int)
C++ template typedef(C++ 模板类型定义)