Search code examples
c++constructorstlallocator

Why does the STL overload their constructors with/without allocator argument?


in std::vector, why does the stl overload the constructors like that:

vector( const vector& other );
vector( const vector& other, Allocator& a );

Why not just do this?

vector( const vector& other, Allocator& a = Allocator() );

Edit:

Since rvalues can't bind to a non const lvalue, then this can be done instead:

vector( const vector& other, const Allocator& a = Allocator() );

Solution

  • The allocator parameter allows the copy to use a specified allocator. The standard provides both constructors because they have fundamentally different properties.

    The version with no allocator parameter will make a copy using the same allocator as other. Whereas the version with a specified allocator will make a copy using that allocator. Your suggestion of providing a default allocator makes distinguishing between these two versions impossible.

    Here's what the documentation says:

    vector(const vector& other) :

    Copy constructor. Constructs the container with the copy of the contents of other.

    The allocator is obtained as if by calling std::allocator_traits<allocator_type>::select_on_container_copy_construction( other.get_allocator())

    vector(const vector& other, const Allocator& alloc) :

    Constructs the container with the copy of the contents of other, using alloc as the allocator.

    The template parameter Allocator is only deduced from the first argument while used in class template argument deduction.