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)
 constructorsoperator=
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.
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