Is the memory in std::array contiguous?
Is the memory in std::array
contiguous? Is the following valid/good practice?
std::array<type1,Num开发者_运维技巧> arr = //initialize value
type1 * ptr = &arr[0];
Could I then pass ptr
to functions expecting a c-style array?
Yes, it is contiguous, as it is basically (and actually) a type arr[10];
, but with STL like interface. It also doesn't decay to a pointer on the slightest provocation.
You can safely pass &arr[0]
to a function expecting a C-style array, that's the design goal of it. To use it with the STL algorithms however, just use the begin
and end
functions:
// either members
std::sort(arr.begin(), arr.end());
// or free from <iterator>
std::sort(std::begin(arr), std::end(arr));
For the language lawyer part, §23.3.2.1 [array.overview] p1
:
The header
<array>
defines a class template for storing fixed-size sequences of objects. An array supports random access iterators. An instance ofarray<T, N>
storesN
elements of typeT
, so thatsize() == N
is an invariant. The elements of anarray
are stored contiguously, meaning that ifa
is anarray<T, N>
then it obeys the identity&a[n] == &a[0] + n
for all0 <= n < N
.
And §23.3.2.1 [array.overview] p2
:
An array is an aggregate (8.5.1) that can be initialized with the syntax
array<T, N> a = {
initializer-list};
Also, in p3
, listing the members of std::array
:
T elems[N]; // exposition only
[ Note: The member variableelems
is shown for exposition only, to emphasize thatarray
is a class aggregate. The nameelems
is not part ofarray
’s interface. —end note ]
Yes the memory of std::array
is contiguous. On VC10, it is declared as:
template<class _Ty,
size_t _Size>
class array
{ // fixed size array of values
...
_Ty _Elems[_Size == 0 ? 1 : _Size];
};
Where _Elemes
is nothing but a simple array of given type.
精彩评论