Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::array member functions empty(), max_size() - useless but for consistency?

Are these member functions as useless as they seem and exist just to provide consistency with other containers?

For example:

std::array<int, 4> array1;  // size of 4 (but no elements initialized)
std::array<int, 0> array2;  // size of zero.

array1.empty();  // false - not empty even though no elements are initialized
array2.empty();  // true - empty and no way to add elements

array1.size();      // room for four now
array1.max_size();  // room for four forever

array2.size();      // no room for anything now
array2.max_size();  // ... or ever

The answer to "Why is std::array< T, 0 > not empty?" deals with a zero "size" param and a non-zero return from sizeof(), i.e., it does take up space even when empty. But that is not what I am asking.

like image 814
Arbalest Avatar asked Dec 15 '22 23:12

Arbalest


2 Answers

Yes, they are only there for consistency, allowing easier template specialisation.
Still your comment about std::array<int, 4> starting with no elements is wrong: It's a dressed up int[4], now and forever.
To your aside, per standard no most-derived C++ object is ever smaller than 1.

like image 168
Deduplicator Avatar answered Mar 02 '23 01:03

Deduplicator


You are wrong about a couple of things:

std::array<int, 4> array1;  // size of 4 but no elements

Not true. This array has 4 elements. It can only have 4.

array1.empty();  // false - no elements, but not empty

No, the array has 4 elements (it can only have 4). So it is not empty.

std::arrays are fixed size, and their size is determined by their type, not by whether any value has been assigned to their elements.

But you are right about the consistency argument: containers are required to have size() and empty() methods. For std::array not to have them would have required special rules. Having these methods makes is easier to use std::array in generic code.

like image 44
juanchopanza Avatar answered Mar 02 '23 00:03

juanchopanza