零长度数组的指针的属性 [英] Properties of a pointer to a zero length array

查看:84
本文介绍了零长度数组的指针的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑

int main()
{
    auto a = new int[0];
    delete[] a; // So there's no memory leak
}

在复制初始化和删除之间,是否允许您读取a + 1处的指针?

Between the copy initialisation and deletion, are you allowed to read the pointer at a + 1?

此外,该语言是否允许编译器将a设置为nullptr?

Furthermore, does the language permit the compiler to set a to nullptr?

推荐答案

    auto a = new int[0];

根据 [basic.compound.3] ,该值a中存储的必须是以下之一:

According to [basic.compound.3], the value stored in a must be one of the following:

  1. 指向对象(类型为int)的指针
  2. 指针超出对象末尾
  3. 无效
  1. A pointer to an object (of type int)
  2. A pointer past the end of an object
  3. Null
  4. Invalid

我们可以排除第一种可能性,因为没有构造类型为int的对象.排除了第三种可能性,因为C ++要求返回非空指针(请参见

We can rule out the first possibility since there were no objects of type int constructed. The third possibility is ruled out since C++ requires a non-null pointer to be returned (see [basic.stc.dynamic.allocation.2]). Thus we are left with two possibilities: a pointer past the end of an object or an invalid pointer.

我倾向于将a看作是过去的指针,但是我没有可靠的参考来明确地确定这一点. (不过, [basic.stc]中对此有很强的暗示作用,看看如何delete此指针.)因此,我将在此答案中同时考虑这两种可能性.

I would be inclined to view a as a past-the-end pointer, but I don't have a reputable reference to definitively establish that. (There is, though, a strong implication of this in [basic.stc], seeing how you can delete this pointer.) So I'll entertain both possibilities in this answer.

在复制初始化和删除之间,是否允许您读取a + 1处的指针?

行为未定义,具体取决于 [expr.add.4] ,无论以上哪种可能性适用.

The behavior is undefined, as dictated by [expr.add.4], regardless of which possibility from above applies.

如果a是过去的指针,则认为它指向没有元素的数组的索引0处的假设元素.仅在0≤0+j≤n时定义将整数j添加到a,其中n是数组的大小.在我们的情况下,n为零,因此仅当j0时才定义和a+j.特别地,添加1是不确定的.

If a is a past-the-end pointer, then it is considered to point to the hypothetical element at index 0 of an array with no elements. Adding the integer j to a is defined only when 0≤0+j≤n, where n is the size of the array. In our case, n is zero, so the sum a+j is defined only when j is 0. In particular, adding 1 is undefined.

如果a无效,则我们明确地陷入否则,行为未定义". (毫不奇怪,所定义的情况仅覆盖有效的指针值.)

If a is invalid, then we cleanly fall into "Otherwise, the behavior is undefined." (Not surprisingly, the cases that are defined cover only valid pointer values.)

此外,该语言是否允许编译器将a设置为nullptr?

不.来自上述 [basic.stc.dynamic.allocation.2 ] :如果请求成功,则可替换分配函数返回的值为非空指针值"..还有脚注指出了C ++ (而不是C)需要一个非空指针来响应零请求.

No. From the above-mentioned [basic.stc.dynamic.allocation.2]: "If the request succeeds, the value returned by a replaceable allocation function is a non-null pointer value". There is also a footnote calling out that C++ (but not C) requires a non-null pointer in response to a zero request.

这篇关于零长度数组的指针的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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