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