1

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?

cmax
  • 13
  • 4
  • 1
    If you run out of memory you have bigger problems. If you are running on a limited memory platform (eg embedded), this should be a design issue. – Richard Critten Sep 18 '19 at 09:18
  • @RichardCritten: It is an limited embedded platform and I am building a databuffer with specialized buffer-overrun-technqieues (think of filtering entries). Running in out of mem should normally not happen because I introduce a max_buffer_size. But if max_buffer_size is reached OR system is out of memory, I want to detect it to "filter" my buffer. – cmax Sep 18 '19 at 09:40

3 Answers3

3

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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.

Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52
0

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...
}
lubgr
  • 37,368
  • 3
  • 66
  • 117