Home > Backend Development > C++ > 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
Release: 2024-11-19 22:36:03
Original
1032 people have browsed it

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 };
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template