C++ Destructor and Cleanup
Series navigation: Previous: The Rule of Three / Rule of Five | Next: RAII Resource Acquisition Is Initialization
A destructor runs when an object lifetime ends.
Use it to release resources owned by the object.
Examples:
- delete heap memory
- close a file
- close a socket
- unlock or release a handle
- free a C library resource
Destructor syntax
The destructor has the class name with ~.
It has no return type and no parameters.
Scope cleanup
For stack objects, the destructor runs automatically when the scope ends.
Expected output:
Cleanup when exception happens
If an exception leaves a scope, C++ destroys stack objects before leaving that scope.
This is called stack unwinding.
Expected output:
The important part:
The destructor still ran, even though run() did not finish normally.
Heap object cleanup
For raw heap objects, the destructor runs only when you call delete.
If you forget delete, the destructor does not run and the resource leaks.
Modern C++ usually avoids raw new and delete.
Prefer:
std::unique_ptr deletes the object automatically when it goes out of scope.
Destructors should not throw
A destructor should not throw exceptions.
Bad idea:
If another exception is already active and the destructor throws, the program can terminate.
Use destructors for cleanup that must always happen.
If cleanup can fail, handle the error inside the destructor or provide an
explicit close() function that the caller can check.
Full example
Expected idea:
The file is closed even though save() throws.
Rule of thumb
- Put cleanup in the destructor.
- Stack objects are destroyed automatically at scope exit.
- Stack objects are also destroyed when an exception leaves the scope.
- Raw heap objects need
delete. - Prefer smart pointers and standard library RAII types.
- Do not throw from destructors.
Run online
Copy the exception cleanup example and run it in the embedded OneCompiler C++ runtime.
Other online compilers: OneCompiler | Compiler Explorer | Wandbox
Run locally
Save the full example as main.cpp:
Series navigation: Previous: The Rule of Three / Rule of Five | Next: RAII Resource Acquisition Is Initialization