int arr[] = {1, 2, 3, 4, 5, 6};
int size = *(&arr + 1) - arr;
- Массив
arr
имеет тип int [6]
, т.е. массив из шести элементов типа int
.
- Выражение
&arr
имеет тип int (*)[6]
, т.е. указатель на (массив из шести элементов типа int
).
- В выражении
&arr + 1
к указателю применяется арифметика указателей. Значение указателя наращивается на sizeof(int[6])
байт, что равно sizeof(int) * 6
байт. Получившийся указатель указывает на гипотетический массив из шести элементов типа int
, следующий непосредственно за массивом arr
.
- В выражении
*(&arr + 1)
происходит разыменование указателя. Т.е. мы получаем lvalue «ссылающееся» на гипотетический массив после массива arr
UB-1). Тип этого выражения — int[6]
3).
- В выражении
*(&arr + 1) - arr
оба операнда бинарного оператора -
имеют тип массива — int [6]
. И к обоим операндам применяется неявное преобразование из типа массива к типу указателя на первый элемент массива.
Т.е гипотетический массив *(&arr + 1)
после массива arr
типа int [6]
преобразуется к указателю типа int*
на свой первый элемент.
Аналогично массив arr
преобразуется к указателю на свой первый элемент.
- Разность двух указателей типа
int*
даёт знаковое целочисленное значение типа std::ptrdiff_t, равное количеству объектов типа int
между двумя указателямиUB-2).
- Разыменование указателя на гипотетический элемент после массива вызывает неопределённое поведение, так как такой указатель не является указателем на объект.
basic.compound / 3:
... Every value of pointer type is one of the following:
- a pointer to an object or function (the pointer is said to point to the object or function), or
- a pointer past the end of an object ([expr.add]), or
- the null pointer value for that type, or
- an invalid pointer value.
expr.unary.op / 1:
The unary *
operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue
referring to the object or function to which the expression points.
Код
constexpr static int arr[] = {1, 2, 3, 4, 5, 6};
constexpr std::ptrdiff_t diff = *(&arr + 1) - arr;
может вызвать следующую ошибку компиляции:
//cannot access array element of pointer past the end of object
constexpr std::ptrdiff_t diff = *(&arr + 1) - arr;
^
Даже если бы было известно, что по адресу на который указывает указатель на гипотетический элемент после последнего расположен объект, то такой указатель по прежнему нельзя разыменовывать. Код
constexpr static int arr[2][2] = {{0, 1}, {2, 3}};
constexpr int val = arr[0][2];
может вызвать следующую ошибку компиляции:
//read of dereferenced one-past-the-end pointer is not allowed in a constant expression
constexpr int val = arr[0][2];
^
- Разность двух указателей, указывающих на элементы разных массивов, вызывает неопределённое поведение.
expr.add / 5:
When two pointer expressions P
and Q
are subtracted, the type of the result is an implementation-defined signed integral type; this type shall be the same type that is defined as std::ptrdiff_t
in the <cstddef>
header.
- If
P
and Q
both evaluate to null pointer values, the result is 0
.
- Otherwise, if
P
and Q
point to, respectively, array elements i
and j
of the same array object x
, the expression P - Q
has the value i − j
.
- Otherwise, the behavior is undefined.
[Note 1: If the value i − j
is not in the range of representable values of type std::ptrdiff_t
, the behavior is undefined. — end note]
Код
constexpr static int arr[2][2] = {{0, 1}, {2, 3}};
constexpr const int* p00 = &arr[0][0];
constexpr const int* p10 = &arr[1][0];
constexpr std::ptrdiff_t diff = p10 - p00;
Может вызвать ошибку компиляции:
//subtracted pointers are not elements of the same array
constexpr std::ptrdiff_t diff = p10 - p00;
^
- Результат разыменования указателя на тип
T
— это lvalue типа T
(не ссылка).
expr.unary.op / 1:
The unary *
operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T
”, the type of the result is “T
”.
Выражение наподобие std::is_same_v< int ( & ) [6], decltype(*(&arr + 1)) >
возвращает true
в силу особенностей работы спецификатора decltype
, который для lvalue
типа T
в качестве типа выводит T&
.
dcl.type.decltype / 1:
For an expression E
, the type denoted by decltype(E)
is defined as follows:
...
otherwise, if E
is an lvalue, decltype(E)
is T&
, where T
is the type of E
;
...
Итого: приведённый в вопросе код содержит неопределённое поведение. Результат его выполнения (если вообще скомпилируется) не предсказуем.