Provide a wrapper for STL allocators, respecting bslma
semantics.
More...
Detailed Description
- Outline
-
-
- Purpose:
- Provide a wrapper for STL allocators, respecting
bslma
semantics.
-
- Classes:
-
- See also:
- Component bslma_stdallocator
-
- Description:
- This component provides a single, mechanism class,
bslalg::ContainerBase
, that can used as a common base class for all STL-style containers. A container should derive from this class to take advantage of empty-base optimization when a non-'bslma' allocator is used.
-
- Usage:
- This section illustrates intended use of this component.
-
- Example 1: Creating a Fixed-Size Array with bslalg::ContainerBase:
- Suppose we would like to implement a fixed-size array that allocates memory on the heap at construction.
- First, we define the interface of the container,
MyFixedSizeArray
, that derives from ContainerBase
. The implementation is elided for brevity: template <class VALUE, class ALLOCATOR>
class MyFixedSizeArray : private bslalg::ContainerBase<ALLOCATOR>
{
Notice that to use this component, a class should derive from ContainerBase
in order to take advantage of empty-base optimization.
VALUE *d_array;
const int d_size;
public:
MyFixedSizeArray(int size, const ALLOCATOR& allocator = ALLOCATOR());
MyFixedSizeArray(const MyFixedSizeArray& original,
const ALLOCATOR& allocator = ALLOCATOR());
~MyFixedSizeArray();
VALUE& operator[](int i);
int size() const;
};
Finally, assuming we have a STL compliant allocator named Allocator
, we can create a MyFixedSizeArray
object and populate it with data. MyFixedSizeArray<int, Allocator<int> > fixedArray(3);
fixedArray[0] = 1;
fixedArray[1] = 2;
fixedArray[2] = 3;
assert(fixedArray[0] == 1);
assert(fixedArray[1] == 2);
assert(fixedArray[2] == 3);