Default std :: vector concatenation and constructor padding

I had a pretty quick question. 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 some special reason why the default constructor is not implemented with a default of 0 for the first parameter in the padding constructor? I can imagine there must be a reason, but I cannot immediately see it.

+3


source to share


2 answers


Because you cant only pass allocator

without providing count

or default element (aka value

)?

Putting count

in 0

will result in an ambiguity error.



It would be much easier if C ++ called params like Python. Boost has such a library , but again, which imposes some runtime overhead :( (can't remember how much now) I've used this Lib a lot in testing, but not where performance is important ...

+4


source


This is because constructors have different requirements for the type contained in the vector. To use the second, the type must be constructive for copying, and if you use the default argument for value

, it must also be the default. The first constructor does not impose such requirements on the contained type.

Note that the constructors you show in the question only existed prior to C ++ 11. There was enough to differentiate between the two scenarios (since any type stored in std::vector

had to be copyable). 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()
);

      



This is because it std::vector

no longer requires its contained types to be copy-constructibe; sufficient for movement. So a count-only constructor requires default construct (but not construct), and prototype count + constructor requires text construct (but not default construct).


The evolution of constructors is std::vector

really quite complicated. See their page on cppreference to see how much they've evolved. This evolution involves adding an optional parameter allocator

to the count-only constructor in C ++ 14, which was (I assume) mistakenly omitted.

+3


source







All Articles