BDE 4.14.0 Production release
|
Macros | |
#define | bslalg_AutoArrayDestructor bslalg::AutoArrayDestructor |
This alias is defined for backward compatibility. | |
Provide a proctor for destroying arrays.
This component provides a proctor object to manage a contiguous (in-place) sequence of otherwise-unmanaged instances of a user-defined type. If not explicitly released, all objects managed by the proctor object are automatically destroyed by the proctor's destructor, using the bslalg_arraydestructionprimitives .
In most instances, bslma::AutoDestructor
can also be used, but this component is more useful in cases where it is simpler to think in terms of two pointers at the ends of the array being managed, rather than an origin and offset.
In this section we show intended use of this component.
In most instances, the use of a bslalg::AutoArrayDestructor
could be handled by a bslma::AutoDeallocator
, but sometimes it is conceptually clearer to frame the problem in terms of a pair of pointers rather than a pointer and an offset.
Suppose we have a class, UsageType
that allocates a block of memory upon construction, and whose constructor takes a char
. Suppose we want to create an array of elements of such objects in an exception-safe manner.
First, we create the type UsageType
:
Then, in main
, we create a TestAllocator
to supply memory (and to verify that no memory is leaked):
Next, we create the pointer for our array:
Then, we declare a string of characters we will use to initialize the UsageType
objects in our array.
Next, we verify that even right after exceptions have been thrown and caught, no memory is outstanding:
Then, we allocate our array and create a guard to free it if a subsequent allocation throws an exception:
Next, we establish an AutoArrayDestructor
on array
to destroy any valid elements in array
if an exception is thrown:
Notice that we pass arrayElementProctor
pointers to the beginning and end of the range to be guarded (we start with an empty range since no elements have been constructed yet).
Then, we iterate through the valid chars in DATA
and use them to construct the elements of the array:
Next, construct the next element of array
:
Now, move the end of arrayElementProctor
to cover the most recently constructed element:
At this point, we have successfully created our array.
Then, release the guards so they won't destroy our work when they go out of scope:
Next, exit the exception testing block:
Then, verify that the array we have created is as expected:
Finally, destroy & free our work and verify that no memory is leaked:
#define bslalg_AutoArrayDestructor bslalg::AutoArrayDestructor |