简体   繁体   中英

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.

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 (ie string , vector ), the standard requires a length_error to be thrown.

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM