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.

4

2 回答 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.

于 2014-04-18T18:48:06.010 回答
4

你错了几件事:

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

不对。这个数组有 4 个元素。它只能有4个。

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

不,数组有 4 个元素(它只能有 4 个)。所以它不是空的。

std::arrays是固定大小的,它们的大小由它们的类型决定,而不是由是否为它们的元素分配了任何值。

但是您对一致性论点是正确的:容器必须具有size()empty()方法。因为std::array没有它们需要特殊的规则。std::array拥有这些方法使得在通用代码中更容易使用。

于 2014-04-18T19:19:44.370 回答