零大小的数组分配是什么/意味着什么? [英] What does zero-sized array allocation do/mean?

查看:97
本文介绍了零大小的数组分配是什么/意味着什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看一些示例代码,并遇到一些零大小的数组分配。我创建了以下代码段以澄清我的问题

Looking at some example code and come across some zero-size array allocation. I created the following code snippet to clarify my question

这是有效的代码:

class T
{
};

int main(void)
{
  T * ptr = new T[0];

  return 0;
}

其用途是什么? ptr是否有效?这个结构是否可移植?

What is its use? Is ptr valid? Is this construct portable?

推荐答案

5.3.4在C ++标准中:

5.3.4 in the C++ Standard:

6 direct-new-declarator 中的每个常量表达式都是一个整数常数表达式(5.19),并且计算结果为严格正值。 direct-new-declarator 中的表达式应具有带非负值的整数或枚举类型(3.9.1)...

6 Every constant-expression in a direct-new-declarator shall be an integral constant expression (5.19) and evaluate to a strictly positive value. The expression in a direct-new-declarator shall have integral or enumeration type (3.9.1) with a non-negative value...

7当 direct-new-declarator 中的表达式的值为零时,调用分配函数,元素。

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.

所以,你的代码分配一个数组,其行为在任何其他数组的T(可以删除删除[],作为参数传递,可能其他事情)。但是,它没有可访问的索引(即读取或写入ptr [0]导致未定义的行为)。

So, your code allocates an array which behaves in every respect like any other array of T (can be deleted with delete[], passed as a parameter, probably other things). However, it has no accessible indexes (that is, reading or writing ptr[0] results in undefined behaviour).

在这个上下文中,常量表达式和表达式不是实际表达式是编译时常数(这显然是0),而是它是否指定多维数组的最后维。语法在5.3.4中定义:1。

In this context the different between the constant-expression and the expression is not whether the actual expression is compile time constant (which obviously 0 is), but whether it specifies the "last" dimension of a multi-dimensional array. The syntax is defined in 5.3.4:1.

这篇关于零大小的数组分配是什么/意味着什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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