tags:

views:

831

answers:

3

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

A: 

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.

Nils Pipenbrinck
+5  A: 

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.

NeARAZ
A: 

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.