Reputation: 3224
I had a fairly quick question. The std::vector provides the following two constructors:
explicit vector( const Allocator& alloc = Allocator()); // default constructor
explicit vector( size_type count, // fill constructor
const T& value = T(),
const Allocator& alloc = Allocator());
Is there any particular reason the default constructor is not implemented with a default value of 0 for the first parameter in the fill constructor? I can imagine there must be a reason but I can't immediately see one.
Upvotes: 3
Views: 737
Reputation: 5673
Because you then can't pass just an allocator
, without providing the count
or default element (aka value
) as well?
Putting count
to 0
will result in ambiguity error.
Would be much more simpler if C++ had named params like Python. Boost has such a library, but again that incurs some runtime overhead :( (can't remember how much right now) I often used this Lib in testing, but not where the performance is important...
Upvotes: 4
Reputation: 171167
The reason is that the constructors place different requirements on the type contained in the vector. To use the second one, the type must copy-constructible, and if you use the default argument for value
, it must be default-constructible too. The first constructor places no such requirements on the contained type.
Note that the constructors you're showing in the question only existed until C++11. There, it was sufficient to differentiate those two scenarios (since any type stored in a std::vector
had to be copy-constructible). C++11 introduced move semantics, and the second constructor was split further:
explicit vector(size_type count);
vector(
size_type count,
const T& value,
const Allocator& alloc = Allocator()
);
That's because std::vector
no longer requires its contained types to be copy-constructibe; move-constructibility is enough. Therefore the count-only constructor requires default constructibility (but not copy constructibility), and the count + prototype constructor requires copy constructibility (but not default constructibility).
The evolution of std::vector
constructors is really quite complex. See their page on cppreference to see how much they've evolved. That evolution includes adding an optional allocator
parameter to the count-only constructor in C++14, which was (I assume) mistakenly omitted.
Upvotes: 3