towi towi - 8 months ago 41
C++ Question

Does std::array<> guarantee allocation on the stack only?


(without myself using
) guaranteed to be allocated in the stack rather then the heap by the C++-Standard?

To be clear, I do not mean
new std::array<int, 10>
. I mainly wonder, if the standard library is allowed to use
inside its implementation.


Could not find more explicit answer in the standard, but [array.overview]/2:

An array is an aggregate ([dcl.init.aggr]) that can be list-initialized with up to N elements whose types are convertible to T.

And [dcl.init.aggr]/1:

An aggregate is an array or a class (Clause [class]) with

  • no user-provided, explicit, or inherited constructors ([class.ctor]),


That about covers it. No way an aggregate could allocate memory dynamically (or perhaps, do anything at all at its own during the construction). There's only an implicitly-declared trivial constructor.

Of course, if you new std::array<...>, you get an array on "the heap".

Some might be more satisfied by what we can get on cppreference:

std::array is a container that encapsulates fixed size arrays.

This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member.

Thirdly, std::array was introduced in C++11. Why? For example, to complement std::vector in some things, like usage in constexpr functions, where dynamic allocation is not allowed.