BDE 4.14.0 Production release
|
Macros | |
#define | bslma_DestructorProctor bslma::DestructorProctor |
This alias is defined for backward compatibility. | |
Provide a proctor to conditionally manage an object.
This component provides a proctor class template, bslma::DestructorProctor
, to conditionally manage an (otherwise-unmanaged) object of parameterized TYPE
supplied at construction. If not explicitly released, the managed object is destroyed automatically when the proctor object goes out of scope by calling the object's destructor. Note that after a proctor object releases its managed object, the same proctor can be reused to conditionally manage another object by invoking the reset
method.
The bslma::DestructorProctor
is normally used to manage objects that are constructed sequentially in a block of memory provided. This is often the case when memory management and primitive helpers are implemented in different components. An example would be the construction of a pair object within another container with the help of a scalar primitive helper (see bslma_constructionutil ). After the first object is constructed in the provided memory, it should be protected in case the constructor of the second object throws. The following example illustrates a typical use of the bslma::DestructorProctor
.
First, suppose we have a pair class similar to std::pair
:
Note that parts of the implementation, including the my_PairTrait
declaration, are elided. The my_PairTrait
will be used by the primitive helper to customize implementations for objects that are pairs.
We now implement the primitive helper:
The implementation of copyConstruct
constructs the pair object in two steps because of the use of allocators. We cannot simply pass the allocator to the copy constructor of the pair object (since std::pair
does not take an allocator). Therefore, we copy construct first
and second
directly in the pair object.
Note that the implementation of my_HasPairTrait
is not shown. It is used to detect whether TYPE
has my_PairTrait
or not (see bslalg_typetraits , bslalg_typetraitpair ).
In the above implementation, if the copy construction of the second object in the pair throws, all memory (and any other resources) acquired as a result of copying the (not-yet-managed) object would be leaked. Using the bslma::DestructorProctor
prevents the leaks by invoking the destructor of the proctored object automatically should the proctor go out of scope before the release
method of the proctor is called (such as when the function exits prematurely due to an exception).
Note that the copyConstruct
method assumes the copy constructor of TYPE::firstType
and TYPE::secondType
takes an allocator as a second argument. In production code, a constructor proxy that checks the traits of TYPE::firstType
and TYPE::secondType
(to determine whether they uses bslma::Allocator
) should be used (see bslalg_constructorproxy ).
#define bslma_DestructorProctor bslma::DestructorProctor |