Let's say I have a function, called like this:
void mysort(int *arr, std::size_t size)
{
std::sort(&arr[0], &arr[size]);
}
int main()
{
int a[] = { 42, 314 };
mysort(a, 2);
}
My question is: does the code of mysort
(more specifically, &arr[size]
) have defined behaviour?
I know it would be perfectly valid if replaced by arr + size
; pointer arithmetic allows pointing past-the-end normally. However, my question is specifically about the use of &
and []
.
Per C++11 5.2.1/1, arr[size]
is equivalent to *(arr + size)
.
Quoting 5.3.1/1, the rules for unary *
:
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 toT
,” the type of the result is “T
.” [ Note: a pointer to an incomplete type (other than cvvoid
) can be dereferenced. The lvalue thus obtained can be used in limited ways (to initialize a reference, for example); this lvalue must not be converted to a prvalue, see 4.1. —end note ]
Finally, 5.3.1/3 giving the rules for &
:
The result of the unary
&
operator is a pointer to its operand. The operand shall be an lvalue ... if the type of the expression isT
, the result has type “pointer toT
” and is a prvalue that is the address of the designated object (1.7) or a pointer to the designated function.
(Emphasis and ellipses mine).
I can't quite make up my mind about this. I know for sure that forcing an lvalue-to-rvalue conversion on arr[size]
would be Undefined. But no such conversion happens in the code. arr + size
does not point to an object; but while the paragraphs above talk about objects, they never seem to explicitly call out the necessity for an object to actually exist at that location (unlike e.g. the lvalue-to-rvalue conversion in 4.1/1).
So, the questio is: is mysort
, the way it's called, valid or not?
(Note that I'm quoting C++11 above, but if this is handled more explicitly in a later standard/draft, I would be perfectly happy with that).