Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does std::array brace initialize?

Since array has no constructors or destructors and no public non-static member variables, how does array allow brace initialization? Trying to initialize the following type is not allowed:

template<typename T, std::size_t num>
class Array
{
    T data[num];
};

How can I write this type in a way that it is brace initializable without any constructors or destructors to keep the type trivially constructible and destructible, and without exposing the private array member?

like image 658
Andreas Loanjoe Avatar asked Aug 16 '26 08:08

Andreas Loanjoe


1 Answers

The constructor to std::array is implicitly declared.

Assuming std::array is defined as

template<
    class T,
    std::size_t N
> struct array;

It contains only one member, T[N], which has public access.

So therefore it's possible to initialise std::array by writing the appropriate syntax for aggregate initialization, i.e. by using braces.

like image 149
Bathsheba Avatar answered Aug 17 '26 21:08

Bathsheba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!