Question

Out of curiosity, I had a look at the LLVM implementation of std::array, and noticed that it is a struct. Most other STL containers I've looked at (vector, queue, map) are classes. And it appears in the standard as a struct so is intentional.

Anyone know why this might be?

Était-ce utile?

La solution

Technically, it's neither a struct nor a class -- it's a template.

std::array is required to be an aggregate. To make a long story short, this ends up meaning that it can't have anything private -- so it might as well be written as a struct (which defaults to making everything public) instead of a class, (which defaults to making everything private).

If you wanted to you could write it as a class anyway:

template <...>
class array {
public:
// ...

But you need to make everything public anyway, so you might as well use a struct that does that by default.

Autres conseils

std::array is a POD type so that it can be initialized like this:

std::array<int, 5> arr = { 1, 2, 3, 4, 5 };

This is different from the initialization from a initializer_list in that the array does not actually allocate new space for the array elements and moves the data from the initializer list in there, but the data in the brackets (that ends up in the initialized data segment) is the internal representation of the array.

This means that there is no copying or moving, in fact there is no code running to initialize anything. The array is ready to go as soon as your executable is loaded into memory.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top