简体   繁体   中英

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

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?

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.

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.

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

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