Petr Skocik
Petr Skocik

Reputation: 60117

Why is an allocator allowed to override the ctors and dtors of its value_type?

As far as I know, containers are supposed to use std::allocator_traits<Alloc>::construct and std::allocator_traits<Alloc>::destroy which are either Alloc::construct and Alloc::destroy respectively or value_type::value_type and value_type::~value_type (the defaults).

Why allow an allocator to override the default ctor and dtor of its value_type? When is it useful?

Upvotes: 1

Views: 78

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171403

This allows the allocator to construct objects in custom ways.

An example based on standard library features is the std::scoped_allocator_adaptor which will pass an allocator to any objects it constructs (as long as they support construction from allocators). That is useful when you want all elements of a container to use the same allocator as the container itself. When the container's allocator constructs an element it passes itself (or a copy of itself rebound to the element type) to the element.

Another example is if you have huge vectors of a trivial type like double but you don't want to pay the cost of zero-initializing all the vector elements if you're going to re-assign them new values anyway. You can have a custom allocator that does nothing in its construct function, so that the elements are left uninitialized when the vector is resized.

Upvotes: 3

Related Questions