Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not?

后端 未结 13 1376
傲寒
傲寒 2020-11-22 06:34

I have seen it asserted several times now that the following code is not allowed by the C++ Standard:

int array[5];
int *array_begin = &array[0];
int *ar         


        
13条回答
  •  失恋的感觉
    2020-11-22 06:54

    It should be undefined behaviour, for the following reasons:

    1. Trying to access out-of-bounds elements results in undefined behaviour. Hence the standard does not forbid an implementation throwing an exception in that case (i.e. an implementation checking bounds before an element is accessed). If & (array[size]) were defined to be begin (array) + size, an implementation throwing an exception in case of out-of-bound access would not conform to the standard anymore.

    2. It's impossible to make this yield end (array) if array is not an array but rather an arbitrary collection type.

提交回复
热议问题