A destructor is a special member function that runs automatically when an object’s lifetime ends and releases the resources that the object owns, such as heap memory, file handles, sockets, locks or database connections. In object-oriented programming, the destructor is the counterpart of the constructor: the constructor establishes the class invariant and acquires resources, while the destructor restores the environment by giving those resources back.
How and when a destructor runs depends heavily on the language. In C++ and Rust, destruction is deterministic: it happens at a known point in the program, typically at the end of a scope. In garbage-collected languages such as Java, C# and Python, the closest equivalent is a finalizer, whose timing is decided by the runtime and is often unpredictable.
How a destructor runs at the end of an object’s lifetime
A destructor runs when the storage of an object is about to be reclaimed, and its job is to leave no resource leaked. For an automatic (stack) object in C++, that moment is the closing brace of the enclosing scope. For a heap object, it is the explicit delete call or the moment the last owning smart pointer releases it. For a temporary, it is normally the end of the full expression that created it.
Destruction follows a strict reverse order of construction. Inside one object, the destructor body runs first, then the data members are destroyed in the reverse order of their declaration, and finally the base class destructors run, again in reverse order. Local objects in a scope are likewise destroyed in last-in, first-out order, which guarantees that an object never outlives something it depends on.
The following table summarizes the moments that trigger destruction for the main storage durations in C++.
| Storage duration | Destruction trigger | Typical example |
|---|---|---|
| Automatic | End of the enclosing scope | A local std::string inside a function |
| Dynamic | delete or the last owner releasing it | An object held by std::unique_ptr |
| Static | Normal program termination, reverse order | A global configuration object |
| Thread | Exit of the owning thread | A thread_local cache |
| Temporary | End of the full expression | A string returned by value and not bound |
Destructors and the RAII idiom
The most important use of destructors is Resource Acquisition Is Initialization (RAII), an idiom in which every resource is owned by an object whose destructor releases it. Because the language guarantees that destructors run during normal exit and during stack unwinding after an exception, cleanup cannot be forgotten or skipped by an early return.
RAII turns resource management into a property of scope. A std::lock_guard releases a mutex, a std::fstream closes its file, and a std::vector frees its buffer, all without any explicit cleanup code at the call site. Rust applies the same principle through the Drop trait, combined with an ownership model that makes double release impossible at compile time.
A well-written destructor follows a small set of rules, which the next table lists with their reasons.
| Rule | Reason | Consequence of breaking it |
|---|---|---|
| Never throw from a destructor | It may run during stack unwinding | std::terminate ends the program |
| Release only owned resources | Ownership must be unambiguous | Double free or dangling pointers |
| Keep it short and simple | It runs on every exit path | Slow shutdown and hidden failures |
| Avoid calling virtual functions | The derived part is already destroyed | Base version runs unexpectedly |
| Make it virtual in polymorphic bases | Deletion through a base pointer | Undefined behavior and leaks |
Virtual destructors and inheritance
When a class is meant to be used polymorphically, its destructor must be declared virtual. Deleting a derived object through a pointer to its base class with a non-virtual destructor is undefined behavior in C++: in practice, only the base part is destroyed, and resources owned by the derived part leak.
A virtual destructor uses the same dynamic dispatch mechanism as any other virtual function, so the call resolves to the most derived destructor, which then chains up through every base. The common guideline is that a base class destructor should be either public and virtual or protected and non-virtual, the second form preventing deletion through the base pointer altogether.
Since C++11, destructors are implicitly noexcept, and the rule of five states that a class defining a custom destructor usually also needs custom copy and move operations. The modern alternative, the rule of zero, recommends composing classes from members that already manage themselves, so that no custom destructor is needed at all.
Destructors compared with finalizers and disposal patterns
Languages with tracing garbage collection do not offer deterministic destructors, because memory is reclaimed only when the collector decides to run. They provide finalizers for last-chance cleanup and separate explicit disposal patterns for resources that must be released promptly.
The table below compares the mechanisms that different languages use for end-of-life cleanup.
| Language | Mechanism | Timing | Recommended use |
|---|---|---|---|
| C++ | Destructor ~T() | Deterministic, end of scope or delete | All resource release through RAII |
| Rust | Drop trait | Deterministic, when the owner goes out of scope | All resource release |
| C# | Finalizer plus IDisposable | Finalizer nondeterministic, Dispose explicit | using statement for prompt release |
| Java | AutoCloseable, Cleaner | close explicit, cleaner nondeterministic | try-with-resources blocks |
| Python | __del__ and context managers | Usually prompt via reference counting, not guaranteed | with statement for files and locks |
| Swift | deinit | Deterministic under reference counting | Releasing observers and handles |
The key distinction is that a finalizer is a safety net, not a cleanup strategy. Java deprecated Object.finalize for removal because finalizers can delay memory reclamation, resurrect objects and run on an unspecified thread. C# documentation likewise recommends implementing the dispose pattern and calling GC.SuppressFinalize once disposal has happened.
Common mistakes with destructors
Most destructor bugs come from unclear ownership or from assumptions about timing that the language does not guarantee. The following table pairs typical symptoms with their causes and fixes.
| Symptom | Likely cause | Fix |
|---|---|---|
| Memory leak in derived class | Non-virtual base destructor | Declare the base destructor virtual |
| Crash on double free | Shallow copy of an owning pointer | Apply the rule of five or use smart pointers |
| Program aborts during an exception | Destructor throws while unwinding | Catch and log inside the destructor |
| File stays locked in C# or Java | Reliance on finalizer timing | Use using or try-with-resources |
| Objects never destroyed | Reference cycle under reference counting | Use weak references for back links |
- Calling a destructor explicitly on an automatic object leads to a second destruction at scope exit.
- Accessing other global objects from a static object’s destructor risks the static destruction order problem.
- Performing slow I/O in a destructor can make program shutdown hang without any visible error.
In simple terms
A destructor is the cleanup routine an object runs when it is no longer needed. If a constructor is like checking into a hotel room and receiving the key, the destructor is checking out: the key is returned, the room is freed, and the next guest can use it.
In some languages this checkout happens at an exact, predictable moment. In others, a background cleaner comes by eventually, so programmers close important things such as files themselves. The main idea is simple: whatever an object borrows, it should give back.
A practical example
A team maintaining a C++ trading gateway notices that the service slowly runs out of operating system file descriptors after several days of uptime. Investigation shows that a Connection base class has a non-virtual destructor, and that derived TlsConnection objects are deleted through base pointers. The derived destructor, which closes the TLS socket, never runs.
The developers make the base destructor virtual, replace raw owning pointers with std::unique_ptr, and move socket closing into a small RAII wrapper whose destructor is noexcept. After the change, load tests that open and close 200,000 connections show a flat descriptor count, and the leak disappears without any extra cleanup calls in the business logic.