Topic 17 of 27 · Beginner
Why does RAII clean up correctly during exceptions?
An automatic object is destroyed when its scope ends, including stack unwinding after an exception. A resource-owning object can therefore release its resource in its destructor.
C++20; compile with g++ -std=c++20.
Detailed answer
An automatic object is destroyed when its scope ends, including stack unwinding after an exception. A resource-owning object can therefore release its resource in its destructor.
Use vector, string, unique_ptr and lock guards instead of manual paired operations. Acquire a resource into an owner immediately so exceptions cannot bypass cleanup.
Destructors should not throw during unwinding. RAII guarantees cleanup of constructed subobjects, but cannot undo an unrelated external side effect unless the object explicitly models a transaction.
Internal working
Stack unwinding destroys fully constructed objects in reverse construction order. If a constructor fails, already constructed members are destroyed, but the complete object's destructor is not called.
Practical scenario
A file read throws after memory allocation. unique_ptr releases the buffer whereas a manual delete at the end is skipped.
#include <memory>
#include <iostream>
int main(){auto p=std::make_unique<int>(42);std::cout<<*p<<"\n";}Common mistakes
- Throwing from a cleanup destructor.
- Holding an acquired resource in an unowned raw pointer.
Key takeaways
- Tie resources to objects.
- Prefer existing owners.
- Cleanup is not the same as rollback.
Follow-up challenges
- What happens when a constructor throws?
- How can RAII represent a mutex lock?