Suppose I have a std::array<T, n>
and want to take an array reference to its contents (i.e. to the non-exposed elems
array member).
I was surprised to find that std::array<T, n>::data()
returns T *
and not T (&)[n]
, so it seems that some kind of cast is necessary. I can write:
std::array<int, 5> arr;
int (&ref)[5] = *reinterpret_cast<int (*)[5]>(arr.data());
However, this looks ugly and potentially unsafe. Is it legitimate (well-defined) code and is there a better way to do this?
The standard doesn't provide for the underlying implementation of array
, but if it uses int[5]
as the underlying representation, then for that implementation only your cast would be (non-portably) legal. For any other underlying representation you violate the strict aliasing rules and enter undefined behavior.
Instead of trying to return the array as an array, can you use iterator pairs to delimit the range you're interested in, following precedent with the standard library?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With