Home

deleters

Deleters are callables responsible for releasing a resource when it is no longer needed. In programming languages that use automatic resource management, a deleter defines how the resource is destroyed or reclaimed and may be tied to an owning handle or smart pointer.

In C++, the term is most commonly used with smart pointers such as unique_ptr and shared_ptr. The

Best practices for deleters include ensuring they do not throw exceptions and that they correctly match the

Beyond C++, the general concept of a deleter appears in various resource-management patterns where a user-supplied

deleter
determines
how
the
pointee
is
destroyed
when
the
smart
pointer
releases
ownership.
The
default
deleter
for
unique_ptr
is
to
call
the
delete
operator
on
the
stored
pointer;
a
version
for
arrays
uses
delete[].
Both
unique_ptr
and
shared_ptr
can
be
configured
with
a
custom
deleter,
which
can
be
a
function
pointer,
a
function
object
(functor),
or
a
lambda.
A
deleter
may
carry
state,
such
as
a
memory
pool
pointer
or
a
resource
manager,
which
is
captured
in
the
functor
and
kept
with
the
owning
pointer.
Custom
deleters
enable
safe
management
of
resources
beyond
plain
memory,
such
as
file
handles,
sockets,
or
opaque
handles
returned
by
libraries.
resource
type
they
manage.
Deleters
should
be
lightweight
and,
when
possible,
idempotent
to
handle
multiple
releases
gracefully.
They
may
also
perform
resource
reclamation
from
specialized
allocators
or
pools,
or
release
resources
in
a
particular
order
required
by
the
application.
cleanup
function
is
invoked
when
ownership
ends.
In
that
sense,
a
deleter
is
a
modular,
customizable
policy
for
resource
destruction
that
helps
implement
RAII
and
robust
resource
lifetimes.