Provide malloc/free adaptor to bslma::Allocator
protocol.
More...
Namespaces |
namespace | bslma |
Detailed Description
- Outline
-
-
- Purpose:
- Provide malloc/free adaptor to
bslma::Allocator
protocol.
-
- Classes:
-
- See also:
- Component bslma_newdeleteallocator, Component bslma_allocator
-
- Description:
- This component provides an allocator,
bslma::MallocFreeAllocator
, that implements the bslma::Allocator
protocol and supplies memory using the system-supplied (native) std::malloc
and std::free
operators. ,--------------------------.
( bslma::MallocFreeAllocator )
`--------------------------'
| ctor/dtor
| singleton
V
,----------------.
( bslma::Allocator )
`----------------'
allocate
deallocate
The key purpose of this component is to facilitate the use of malloc
and free
when the default bslma::NewDeleteAllocator
is not desirable (such as the case of bslma::TestAllocator
). To accomplish this goal, malloc
and free
are wrapped in a singleton object whose lifetime is guaranteed to exceed any possibility of its use.
-
- Thread Safety:
- A single object of
bslma::MallocFreeAllocator
is safe for concurrent access by multiple threads. The underlying implementation of malloc
and free
will ensure that heap corruption does not occur. Note that this allocator therefore has a stronger thread safety guarantee than is required by the base-class contract or than is provided by other allocators.
-
- Usage:
- This component is intended to be used when the use of
new
and delete
are not desirable, such as the case of bslma::TestAllocator
. Instead of using bslma::Default
which uses the bslma::NewDeleteAllocator
, this component can be used to bypass the use of new
and delete
.
- The following example demonstrates the use of this component for a user defined allocator instead of using the default allocator:
class my_Allocator : public bslma::Allocator {
bslma::Allocator *d_allocator_p;
public:
my_Allocator(bslma::Allocator *basicAllocator = 0);
~my_Allocator();
void *allocate(size_type size);
void deallocate(void *address);
};
The constructor is implemented using bslma::MallocFreeAllocator
.
my_Allocator::my_Allocator(bslma::Allocator *basicAllocator)
: d_allocator_p(basicAllocator
? basicAllocator
: &bslma::MallocFreeAllocator::singleton())
{
}
When the basicAllocator
is not specified, the bslma::MallocFreeAllocator
will be used. That allocator then then calls std::malloc
and std::free
for allocating and deallocating memory.