Exception safety of std::deque operations

Which std::deque operations are exception-safe?

Most operations on std::deque provide strong exception safety, meaning if an exception is thrown, the deque remains in a valid state and no resources are leaked.

Operations that provide strong exception safety include:

  • push_front(), push_back(), emplace_front(), emplace_back()
  • pop_front(), pop_back()
  • insert(), emplace(), erase()
  • clear(), swap()

However, there are a few operations that only provide basic exception safety, meaning if an exception is thrown, the deque is left in a valid but unspecified state.

Operations with basic exception safety:

  • deque(size_type n, const T& value) and deque(InputIt first, InputIt last) constructors
  • operator=
  • assign(), resize()

For these operations, if an exception is thrown during the operation (for example, when copying elements), some elements might be constructed, copied, or destroyed, but the deque will still be in a valid state.

Here's an example of how push_back() maintains strong exception safety:

template <typename T>
void Deque<T>::push_back(const T& value) {
  if (backIndex == blockSize) {
    allocateNewBlock();  
    backIndex = 0;
  }
  try {
    new (&blocks_[backBlock_][backIndex])
      T(value);  
  } catch (...) {
    if (backIndex == 0) {
      deallocateLastBlock();  
    }
    throw;
  }
  ++backIndex;
}

If the constructor of T throws an exception, the deque's state is rolled back by deallocating the block if it was newly allocated.

Double-Ended Queues using std::deque

A guide to double-ended queues - a structure that behaves like a vector, specialised for manipulating objects at the edges of the collection

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Performance differences between std::vector and std::deque
When should I use a std::deque instead of a std::vector for optimal performance?
How std::deque is implemented internally
How does a std::deque store its elements in memory?
Benefits of using emplace over insert
What are the advantages of using emplace_front() or emplace_back() instead of push_front() or push_back()?
Iterator invalidation rules for std::deque
When do std::deque operations invalidate iterators?
Thread safety of std::deque
Is std::deque thread-safe? Can multiple threads access a deque concurrently?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant