BDE 4.14.0 Production release
|
Macros | |
#define | bslma_DeallocatorGuard bslma::DeallocatorGuard |
This alias is defined for backward compatibility. | |
Provide a guard to unconditionally manage a block of memory.
This component provides a guard class template, bslma::DeallocatorGuard
, to unconditionally manage a block of (otherwise-unmanaged) memory. The managed memory is deallocated automatically when the guard object goes out of scope using the deallocate
method of the parameterized ALLOCATOR
(allocator or pool) supplied at construction.
The parameterized ALLOCATOR
type of the bslma::DeallocatorGuard
class template must provide a (possibly virtual
) method:
to deallocate memory at the specified address
(originally supplied by the ALLOCATOR
object).
A bslma::DeallocatorGuard
can be used to ensure that a dynamically allocated raw memory resource is safely deallocated in the presence of multiple return statements or exceptions in an exception-neutral way (i.e., without the need for try
/catch
blocks). In this simple example, consider the function evaluatePassword
which attempts to determine how secure a given password might be:
This function will be implemented in terms of three exception neutral subroutines, each of which operates on a writable copy of the null-terminated password, (perturbing its contents slightly) and requiring unbounded amounts of scratch memory (to be allocated and deallocated from a supplied allocator):
A final subroutine is then used to determine and return the score:
The top-level routine is implemented as follows:
Notice that if any of the initial (numbered) subroutines returns a non-zero status value, the top-level evaluatePassword
routine returns immediately with a predetermined score. Moreover, each of these routines may encounter a bad_alloc exception should the supplied allocator fail to return the requested memory. Even if all of these subroutines evaluates successfully, the score calculated using finalEval
is returned directly by evaluatePassword
, yet we still need to deallocate buffer
. By guarding buffer with a bslma::DeallocatorGuard
as shown above, all of these issues are fully addressed, and the top-level routine is also exception neutral as desired.
#define bslma_DeallocatorGuard bslma::DeallocatorGuard |