What happens is that the compiler must select one of the overloads of the vector
constructor, which allows more than one argument:
explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator()); template <class InputIterator> vector(InputIterator first, InputIterator last, const Allocator& = Allocator());
The first overload (which you want to match) requires argument conversion. The second does not require conversion, since 2 arguments are of the same type. So the overload that the compiler chooses. Unfortunately, the int
type does not have all the operations that the second constructor uses for these arguments.
Forcing arguments to different types by dropping NULL
to int*
or by creating the first argument unsigned ( 1U
), since the correct hints can avoid the problem by forcing the compiler to choose the first constructor option.
Update:
When I compile this with MinGW 4.5.2, I get compilation errors (different, but for the same reason, I think). However, when I create MSVC (2008 or 2010), I get no errors. When I look at the code that MSVC generates, it actually maps the second overload (with 2 iterators), not the "size and default value" overload.
βYeah,β I think, βit will happen somewhere at runtime because iterators with values 1
and 0
make no sense.β
However, when the "iterator" types of this constructor turn out to be int
, the MSVC implementation executes the "count / initial value" vector
construct.
The standard states what this constructor should do if the arguments to the InputIterator
constructor meet the requirements of the InputIterator. Since int
does not meet the requirements of InputIterator, the implementation has some loose control to do something else. The standard says that "an implementation may declare additional non-virtual signatures of member functions within a class" (17.4.4.4), and this, in my opinion, will cover the behavior of MSVC. The behavior that you see and that I see with GCC 4.5.2, which creates error diagnostics, is also allowed by the standard.
I am sure that the behavior of MSVC is what most users want and want (until they move to another compiler for the code). And it is certainly smart.