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() );
CodePudding user response:
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
, usingalloc
as the allocator.The template parameter
Allocator
is only deduced from the first argument while used in class template argument deduction.
CodePudding user response:
Why not just do this?
vector( const vector& other, Allocator& a = Allocator() );
Because a non const lvalue ref cannot be bound to a temporary so Allocator& a = Allocator()
won't work.
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() );
Even if you were to use a const lvalue ref then that would make vector(vec)
to be ambiguous as the compiler wouldn't know which one of the above two constructors to use.