4

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.

1
  • All elements of a std::array are default initialised, if no explicit initialiser given. Commented Apr 18, 2014 at 19:56

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To be clear, and for other readers, by "aside" you mean that other question I refer to?
yes, just added the info you alluded to with your link, even though it is not important to your question.
4

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.

1 Comment

OK - I corrected the corresponding comments in the sample code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.