Home  >  Article  >  Backend Development  >  Does the C Standard Guarantee the Same Size and Memory Layout for `std::array` as for Built-in Arrays?

Does the C Standard Guarantee the Same Size and Memory Layout for `std::array` as for Built-in Arrays?

Linda Hamilton
Linda HamiltonOriginal
2024-11-19 22:36:03977browse

Does the C   Standard Guarantee the Same Size and Memory Layout for `std::array` as for Built-in Arrays?

Does C Standard Define the Size of std::array?

In C 11, std::array offers contiguous storage with performance comparable to regular arrays. However, it's unclear if std::array's size and memory layout mirror that of normal arrays.

Standard Requirements

The C standard (§23.3.2.1/2) defines an array as an aggregate initialized via:

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

As an aggregate, std::array cannot use constructors to convert data in the initializer-list. This implies that it primarily stores the actual data values.

Potential Implementation-Specific Behavior

Technically, it's possible for an std::array to include auxiliary data or non-standard alignment, which would deviate from a normal array's behavior.

For instance, a compiler could add a sentinel value at the end of an std::array to detect out-of-bounds write attempts. Alternatively, super-alignment (e.g., Intel SSE instructions) could be supported by an std::array but not by a built-in array.

Expected Behavior

In general, you can expect the following code to behave as intended:

std::vector< std::array<int, N> > x(M);
typedef int (*ArrayPointer)[N];
ArrayPointer y = (ArrayPointer) &amp;x[0][0];
// Use y as a multidimensional array

Most compilers (e.g., GNU and Intel) adhere to this behavior. However, it's important to note that the standard does not explicitly guarantee identical memory layout for std::array and normal arrays.

The above is the detailed content of Does the C Standard Guarantee the Same Size and Memory Layout for `std::array` as for Built-in Arrays?. 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