Is the Size of std::array Enforced by the Standard?
In C 11, std::array is guaranteed to have contiguous storage and a performance that surpasses or equals a regular array. However, the question remains: does the standard explicitly define the size and memory layout of std::array?
Exploring the Standard's Requirements
The standard defines std::array as an aggregate that can be initialized using the syntax:
std::array<T, N> a = { initializer-list };
As an aggregate, std::array cannot employ constructors to convert data from the initializer list. This implies that the array primarily stores the values themselves.
Possible Deviations from Expected Behavior
Technically, the standard does not prohibit certain potential deviations:
Compiler Variations
Despite the standard's ambiguity, practical usage in major compilers like GNU and Intel suggests that std::array's size and memory layout mirror those of regular arrays.
std::vector< std::array<int, N> > x(M); typedef int (*ArrayPointer)[N]; ArrayPointer y = (ArrayPointer) &x[0][0]; // Safe multidimensional array-like usage
It's crucial to note that while this code functions as expected, it's not a guarantee that all implementations will follow this pattern. Therefore, relying on this behavior is not advisable in mission-critical code.
The above is the detailed content of Does the C Standard Guarantee the Size and Memory Layout of `std::array`?. For more information, please follow other related articles on the PHP Chinese website!