Can max_size() be undefined behavior?

138 Views Asked by At

In the C++ standard, max_size() is defined as

Returns: distance(begin(), end()) for the largest possible container.

- [container.reqmts] max_size

Initially, this looks good, and there is no Preconditions paragraph. However, std::distance returns (last - first) ([iterator.operations] p5) and this is possibly undefined behavior for random access iterators (note the Preconditions in [iterator.requirements] b - a).

What is the standard actually trying to say here?

  1. max_size() has no preconditions, so while it isn't explicitly stated, the largest possible container is required to have a max_size() so that distance(begin(), end()) is well-defined.

  2. max_size() is missing a Preconditions paragraph, and it's possible for max_size() to be undefined behavior if end() - begin() and by proxy, std::distance(begin(), end()) is UB.

  3. Something else.

The underlying question is:

Does the absence of a Preconditions paragraph impose requirements on the implementation, or is it an editorial mistake?

There might not be a clear answer to this. std::distance is defined in terms of (last - first), which can be undefined behavior, but std::distance also doesn't have a precondition which requires that the iterator difference is representable. It's not plausible that &b - &a is UB but std::distance(&a, &b) is well-defined.

Based on this, I think it's an editorial mistake, max_size() is missing a precondition, and can be undefined. However, I may be missing something here.

0

There are 0 best solutions below