Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design decision regarding std::array fill

Tags:

c++

c++11

std::array in C++11 is a useful class that provides a C++ Container interface over a C stack array.

But why does std::array not have the typical fill constructor that most containers have? Instead, it has a method fill.

Is there some reason why std::array is unique among STL containers in this regard?

like image 561
Channel72 Avatar asked Aug 09 '13 20:08

Channel72


3 Answers

From section 23.3.2.1:

An array is an aggregate (8.5.1) that can be initialized with the syntax array a = { initializer-list };

If it worked like std::vector it wouldn't be a POD anymore. Additionally from the same section:

The conditions for an aggregate (8.5.1) shall be met.

These conditions are:

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

like image 123
Borgleader Avatar answered Oct 21 '22 21:10

Borgleader


Yes; std::array is meant to be an aggregate (C++11 §8.5.1) so that at can be used in as many contexts as possible where a plain array can be used. An aggregate can have no explicit constructors or destructor.

like image 5
Casey Avatar answered Oct 21 '22 20:10

Casey


Everybody's explained the "why" pretty well I think, so I'll just put up a workaround suggestion, which should compile to be just as good as a native constructor:

template< typename T, std::size_t n > std::array<T,n> filledArray( const T& v ) {
    std::array<T,n> r;
    r.fill( v );
    return r;
}

auto arr = filledArray<int,4>( 7 );
like image 3
Dave Avatar answered Oct 21 '22 22:10

Dave