fredoverflow fredoverflow - 6 months ago 24
C++ Question

How do I implement array::max_size()?

I am building my own

array<T, n>
class template for fun and education. The C++0x standard draft specifies a member function
for all containers as
distance(begin(), end())
"for the largest possible container". How do I implement this member function for arrays? Do I simply return
, or should the result depend on the element type?

Hmm, both
from current g++ and

#include <array>
#include <boost/array.hpp>
#include <iostream>

int main()
std::array<int, 11> foo;
std::cout << foo.max_size() << std::endl; // prints 11

boost::array<int, 11> bar;
std::cout << bar.max_size() << std::endl; // prints 11

Answer Source

I agree that the draft is somewhat lacking here.

It is unclear whether container here references:

  • any container
  • any container of this family
  • any container of a given instance of this family

Unlike @Jerry I would lean toward the latter option.

Looking at basic_string::append, the description states:

Throws: length_error if size() + n > max_size()

With this remark, I think that the Standard puts its foot in the door for the specification of generic algorithms whose behavior would differ based on whether or not the Container they are operating on can be expanded or not, which can be checked with max_size.

As such, a Container should logically returns its maximum length.

Therefore, std::size_t std::array<T,n>::max_size() const { return n; } is the logical choice.

Note that this same max_size definition would logically be applicable to fixed-sized allocators (and notably, stack-based allocators as written by Howard Hinnant).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download