FrozenHeart
FrozenHeart

Reputation: 20766

size greater than max_size in containers

What standard says about situation when size of the container is greater than max_size?

UB, std::bad_alloc or something else?

MSVC throws an exception.

Upvotes: 3

Views: 830

Answers (2)

Adam Rosenfield
Adam Rosenfield

Reputation: 400700

The standard requires a std::length_error to be thrown in most cases, but in some cases the allocator may throw a different exception.

From C++03 §21.3/4a (Class template basic_string):

For any string operation, if as a result of the operation, size() would exceed max_size() then the operation throws length_error.

§21.3.3/10-12 (basic_string capacity):

void reserve(size_type res_arg=0);
[...]
Throws: length_error if res_arg > max_size().218)

218) reserve() uses Allocator::allocate() which may throw an appropriate exception.

§23.2.4.2/2-4 (vector capacity):

void reserve(size_type n)
[...]
Throws: length_error if n > max_size().248

248) reserve() uses Allocator::allocate() which may throw an appropriate exception.

The standard doesn't explicitly mention this for the other standard containers (deque, list, priority_queue, map, multimap, set, multiset, and bitset). However, in Table 65 (Container requirements), it says that max_size is the "size() of the largest possible container".

Upvotes: 1

Collin Dauphinee
Collin Dauphinee

Reputation: 14003

I'm assuming you mean 'what happens if I try to push the container over max_size?' because a container's size cannot exceed max_size. If it does, then max_size returned an incorrect value.

Exactly what happens depends on the container and what operation is attempting to resize the container, but in the case of most re-sizable containers (i.e. string, vector), the standard requires a length_error to be thrown.

Upvotes: 1

Related Questions