零长度数组的指针的属性 [英] Properties of a pointer to a zero length array
问题描述
考虑
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:
- 指向对象(类型为
int
)的指针 - 指针超出对象末尾
- 空
- 无效
- A pointer to an object (of type
int
) - A pointer past the end of an object
- Null
- 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
为零,因此仅当j
为0
时才定义和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屋!