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

Detailed Description

Outline

Purpose

Provide a mechanism to propagate standard allocator state.

Classes

Description

This component provides an allocator adaptor class template, bsltf::StdAllocatorAdaptor, that mostly delegates operations to an allocator object of a (template parameter) allocator type, except that it enables the propagation of the (stateful) allocator object to constructed elements, if appropriate. This class template enables reuse of test cases in higher level components (e.g., containers) written first using bslma::Allocator and bslma::TestAllocator to also test correct allocation using a C++ standard style allocator.

StdAllocatorAdaptor' defines the minimal interface needed in order to comply with section 17.6.3.5 ([allocator.requirements]) of the C++11 standard. This class is similar to the scoped_allocator_adaptor class template that is part of the C++11 standard, except that this adaptor does not support multiple levels of allocators (i.e., it is equivalent to the scoped_allocator_adaptor with a single allocator).

Usage

This section illustrates intended use of this component.

Example 1: Allocator Propagation

bslma::ConstructionUtil propagates bslma::Allocator, wrapped by C++ standard style allocator, to the constructor, if type, being constructed, supports UsesBslmaAllocator trait. bsltf::StdAllocatorAdaptor is used in test drivers to get the same behavior for the types that do not support that trait.

Suppose, we want to adopt a test for a component that uses bslma-style allocation to test that this component correctly works with standard allocators. For simplicity the test below constructs an object of the (template parameter) type TYPE by calling allocator's construct method. We want to test that allocator is correctly propagated to the object constructor. First, we define the test implementation:

template<class TYPE, class ALLOC = bsl::allocator<TYPE> >
class TestDriver
{
public:
static void testCase()
{
bslma::TestAllocator oa("object");
ALLOC xoa(&oa);
xoa.construct(buffer.address(), 1);
const TYPE& X = buffer.object();
assert(1 == X.data());
assert(&oa == X.allocator());
}
};
Definition bslma_destructorguard.h:132
Definition bslma_testallocator.h:384
Definition bsls_objectbuffer.h:276
TYPE * address()
Definition bsls_objectbuffer.h:334
TYPE & object()
Definition bsls_objectbuffer.h:351

Now, parameterize TestDriver class with StdAllocatorAdaptor explicitly to expand testCase behavior for types, that don't support bslma allocators:

template<class TYPE>
class StdBslmaTestDriver : public TestDriver<TYPE,
bsltf::StdAllocatorAdaptor<bsl::allocator<TYPE> > >
{
};

Finally, run the test for types that use bslma and standard allocators:

TestDriver<AllocTestType>::testCase();
StdBslmaTestDriver<StdAllocTestType<bsl::allocator<int> > >::testCase();