Destructor

On this page 7

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 durationDestruction triggerTypical example
AutomaticEnd of the enclosing scopeA local std::string inside a function
Dynamicdelete or the last owner releasing itAn object held by std::unique_ptr
StaticNormal program termination, reverse orderA global configuration object
ThreadExit of the owning threadA thread_local cache
TemporaryEnd of the full expressionA string returned by value and not bound
When destruction is triggered in C++

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.

RuleReasonConsequence of breaking it
Never throw from a destructorIt may run during stack unwindingstd::terminate ends the program
Release only owned resourcesOwnership must be unambiguousDouble free or dangling pointers
Keep it short and simpleIt runs on every exit pathSlow shutdown and hidden failures
Avoid calling virtual functionsThe derived part is already destroyedBase version runs unexpectedly
Make it virtual in polymorphic basesDeletion through a base pointerUndefined behavior and leaks
Rules for writing a correct destructor

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.

LanguageMechanismTimingRecommended use
C++Destructor ~T()Deterministic, end of scope or deleteAll resource release through RAII
RustDrop traitDeterministic, when the owner goes out of scopeAll resource release
C#Finalizer plus IDisposableFinalizer nondeterministic, Dispose explicitusing statement for prompt release
JavaAutoCloseable, Cleanerclose explicit, cleaner nondeterministictry-with-resources blocks
Python__del__ and context managersUsually prompt via reference counting, not guaranteedwith statement for files and locks
SwiftdeinitDeterministic under reference countingReleasing observers and handles
Cleanup mechanisms across languages

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.

SymptomLikely causeFix
Memory leak in derived classNon-virtual base destructorDeclare the base destructor virtual
Crash on double freeShallow copy of an owning pointerApply the rule of five or use smart pointers
Program aborts during an exceptionDestructor throws while unwindingCatch and log inside the destructor
File stays locked in C# or JavaReliance on finalizer timingUse using or try-with-resources
Objects never destroyedReference cycle under reference countingUse weak references for back links
Destructor problems, causes and fixes
  • 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.