BDE 4.14.0 Production release
Loading...
Searching...
No Matches
bdlma_deleter

Detailed Description

Outline

Purpose

Provide a protocol for deleting objects of parameterized type.

Classes

See also
bslma_allocator

Description

This component defines the base-level protocol, bdlma::Deleter, for a thread-safe and type-safe deleter of objects of arbitrary type. This class is extremely useful for transferring the ownership of objects between different entities. The following usage example demonstrates this point.

Usage

This section illustrates intended use of this component.

Example 1: Basic Usage

Suppose that we would like to transfer ownership of an object between threads using bsl::shared_ptr. For the sake of discussion, the type of this object is my_Obj, we will suppose that it is created using a given basicAllocator, and that a concrete implementation of bdlma::Deleter, say my_Deleter, is to be used. Note that we assume that my_Obj does not require an allocator for any of its members:

my_Obj *object = new(basicAllocator) my_Obj;
Definition bslma_newdeleteallocator.h:301

Next, create a concrete deleter for object using the same allocator as was used to allocate its footprint:

my_Deleter deleter(&basicAllocator);

Finally, create a shared pointer passing to it object and the address of deleter:

bsl::shared_ptr<my_Obj> handle(object, &deleter, &basicAllocator);
Definition bslstl_sharedptr.h:1830

Now the handle can be passed to another thread or enqueued efficiently. When the reference count of handle goes to 0, object is automatically deleted via the deleteObject method of deleter, which in turn will invoke the destructor of object. Note that since the type of the deleter used to instantiate handle is bdlma::Deleter<my_Obj>, any kind of deleter that implements this protocol can be passed. Also note, on the downside, that the lifetime of deleter must be longer than the lifetime of all associated instances.