Home >Backend Development >C++ >Does `std::array` have the same size and memory layout as a regular C array?

Does `std::array` have the same size and memory layout as a regular C array?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 22:10:13174browse

Does `std::array` have the same size and memory layout as a regular C   array?

Size of std::array in the C Standard

The C 11 specification for std::array ensures contiguous storage and performance comparable to regular arrays. However, it raises the question of whether std::array has the same size and memory layout as a standard array.

According to §23.3.2.1/2 of the standard, an array is an aggregate that can be initialized using the syntax:

std::array<T, N> a = { initializer-list };

As an aggregate, std::array must store the values from the initializer list directly. While it's theoretically possible for an std::array to store auxiliary data or differ in alignment from a regular array, these possibilities are highly unlikely.

In practice, most compilers treat std::array as a contiguous block of memory with the same size and layout as a regular array. This behavior is supported by third-party documentation and observed in various compilers.

For example, the following code, which accesses an std::array as a multidimensional array pointer, works as expected:

std::vector<std::array<int, N>> x(M);
typedef int (*ArrayPointer)[N];
ArrayPointer y = (ArrayPointer)&x[0][0];
// use y like normal multidimensional array

Based on these observations, it's generally safe to assume that:

sizeof(std::array<int, N>) == sizeof(int) * N

However, it's important to note that this behavior is not strictly guaranteed by the standard. Compilers have some flexibility in how they implement std::array, and future revisions of the standard could alter this behavior.

The above is the detailed content of Does `std::array` have the same size and memory layout as a regular C array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn