← C++ roadmap

Topic 21 of 27 · Expert

How would you design a resource-owning container with strong exception safety?

Define the ownership invariant first: each live allocation has one owner, size counts initialized elements, and every observable state is valid.

Architect / SpecialistSpecialist · 8–10+ yearsArchitecture

C++20; compile with g++ -std=c++20.

Detailed answer

Define the ownership invariant first: each live allocation has one owner, size counts initialized elements, and every observable state is valid.

For operations that may fail, build replacement state before committing it. Copy-and-swap can provide the strong guarantee, while move operations should have truthful noexcept declarations.

Generic containers must distinguish raw storage from constructed objects and destroy only constructed elements. Prefer rule-of-zero composition with standard containers unless custom storage is justified by measured needs.

Internal working

A strong exception guarantee means failure leaves the original observable state unchanged. Allocation, copying and user-defined element construction may all throw at different points.

Practical scenario

A custom buffer grows during append. If element copying fails halfway, destroy the partial replacement and keep the old buffer intact.

#include <vector>
#include <utility>
#include <iostream>
int main(){std::vector<int> original{1,2};auto next=original;next.push_back(3);original.swap(next);std::cout<<original.size()<<"\n";}
Common mistakes
  • Marking throwing moves noexcept.
  • Destroying unconstructed storage.
Key takeaways
  • State ownership invariants.
  • Commit only complete replacement state.
  • Prefer rule-of-zero composition.
Follow-up challenges
  • When is the basic guarantee enough?
  • How do allocator propagation rules change swap?
Practise C++ with the AI mentor

Can't find a C++ topic you need for exams or placements? Request it and we'll add it.