When is it useful to use custom build / destroy methods in allocators?

Custom allocators and, in particular, the ability to customize methods are allocate/deallocate

very useful - they allow you to control the low-level memory allocation strategies used in certain critical areas. Combined node-based container allocators and fixed-size allocators are a few examples that come to mind.

But when is it useful to define custom methods construct/destroy


As I understand it, the standard stipulates that these methods have the same effect as placement new

and explicit destruction, i.e.

//construct should give the same effect as:
    construct (_Type *_ptr, _Type const&_val)
        new(_ptr) _Type(_val);
//destroy should give the same effect as:
    destroy (_Type *_ptr)


Is there a way to implement these methods differently - without using placement new

and explicit destruction? If not, why are they part of the allocator object? Wouldn't it be easier if everyone just used placement new

and direct destruction directly?


source to share

1 answer

For an allocator that replaces the wrapper type around the template argument and instead works on that, construct

and destroy

should call the wrapper constructor and destructor, not the allocated type.

In C ++ 11, construct

passes any number of arguments to the constructor. A custom allocator can insert arguments at the beginning or end of the list, or otherwise intercept and modify arguments. This will only work if the user is using an in-place design.

By the way, you should never use it _Type

as an identifier; identifiers with leading underscores followed by capital are reserved for implementation.



All Articles