What is the sizeof std::array<char, N>? [duplicate]

不打扰是莪最后的温柔 提交于 2019-11-29 13:45:11

Obviously sizeof(std::array<char, N>) != N if N == 0. It also doesn't necessarily hold for N > 0. §23.3.2.1 [array.overview]/p1-2:

The header <array> defines a class template for storing fixed-size sequences of objects. An array supports random access iterators. An instance of array<T, N> stores N elements of type T, so that size() == N is an invariant. The elements of an array are stored contiguously, meaning that if a is an array<T, N> then it obeys the identity &a[n] == &a[0] + n for all 0 <= n < N.

An array is an aggregate (8.5.1) that can be initialized with the syntax

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

where initializer-list is a comma-separated list of up to N elements whose types are convertible to T.

§8.5.1 [dcl.init.aggr]/p1:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

Since array is an aggregate type, it can't have a custom constructor that performs dynamic allocation, and it must store the elements directly since it must be able to be initialized from a initializer list using aggregate initialization. However, nothing in the standard prevents the implementation from adding extra stuff after its C-style array member, as long as array<T, N> a = { initializer-list }; has the defined semantics when the initializer-list contains at most N members. An implementation that looks like

template<typename T, size_t N>
struct array {
    //typedefs and member functions omitted

    T _Elems[N];
    double _Because_I_can;
};
// specialization for N == 0 case omitted

is perfectly legal. Therefore, there's no guarantee that sizeof(std::array<char, N>) == N.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!