Double-Ended Queues using std::deque

Exception safety of std::deque operations

Which std::deque operations are exception-safe?

Vector art representing computer hardware

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved