Howto detect a fail of dynamic memory allocation when pushing to std::deque?

302 Views Asked by At

I am looking for a technique to detect if it is possible or not to push/insert/etc. further elements to a std::deque. It should do dynamic memory allocation for me, but what happens when my memory is full? By using malloc() I would receive a Nullpointer but how to detect a out of memory situation when using a std::deque?

3

There are 3 best solutions below

0
lubgr On BEST ANSWER

Handling out-of-memory situations within standard containers is delegated to the underlying allocator (the second, often not specified template parameter of std::deque). If you go with the default std::allocator, which throws upon failure in std::allocator::allocate, you can wrap the insertion into a try-catch block:

try {
   myDeque.push_back(42);
} catch (const std::bad_alloc& e) {
  // Do something...
}
0
Yksisarvinen On

Use the documentation.

For example, for std::deque::push_back we read:

If an exception is thrown (which can be due to Allocator::allocate() or element copy/move constructor/assignment), this function has no effect (strong exception guarantee).

Assuming your type doesn't throw on copy/move operations, the only possible place to throw is allocator.

std::allocator::allocate() will throw std::bad_alloc on failure:

Throws std::bad_alloc if allocation fails.

1
Some programmer dude On

Allocations by the standard containers are handled by their allocator, which defaults to std::allocator.

The std::allocator allocate function is using operator new for the allocation.

And operator new throws the std::bad_alloc exception if it fails.