For std::map, how will insert behave if it has to resize the container and the memory is not available?

StackOverflow https://stackoverflow.com/questions/104483

  •  01-07-2019
  •  | 
  •  

Question

For std::map, how will insert behave if it has to resize the container and the memory is not available?

Was it helpful?

Solution

STL map does not have to "resize" container. map (just like list) is a node based container; each insert allocates memory.

That said, out of memory situation is handled just like any other out-of-memory situation in C++: it throws a std::bad_alloc. STL containers with default allocators don't do anything fancy, they all end up allocating via standard new/delete operators somehow.

In STL map's case, it will throw exception and will otherwise behave as if it was not called. That is, the container will remain unmodified.

OTHER TIPS

New will throw an exception. Easy as that.

The insert will not happen, and neither will the content of the dictionary be modified or corrupted.

To expand on Nils answer (yes it will throw), but what happens when it throws is sometimes confusing in the spec.

In 17.2.2 of the specification (regarding maps / exceptions), if insert() throws, that function has no effect. This is a strong guarantee for map. This differs from containers using contiguous allocation like vector or deque.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top