C ++ 11 :() or {} in list initialization?
I mean " Working Draft N3337 " which said it most closely resembles the published C ++ 11 standard .
If there are suitable constructors, then it calls the constructors.
Example (p200):
struct S {
// no initializer-list constructors
S(int, double, double); // #1
S(); // #2
// ...
};
S s1 = { 1, 2, 3.0 }; // OK: invoke #1
S s2 { 1.0, 2, 3 }; // error: narrowing
Otherwise it will use aggregate initialization.
Now here is an example using vector
that has an explicit constructor from size_t
and constructor initializer_list
:
vector<double> v1(7); // ok: v1 has 7 elements
vector<double> v1{7}; // ok: v1 has 1 element (with its value 7.0)
Here I am confused. Why is there a different behavior for constructors vector
than for S
?
source to share
Because overloading is initializer_list
strongly preferred by everyone else. From [over.match.list]:
When objects of a non-aggregate class type are
T
initialized over a list (8.5.4), overload resolution selects the constructor in two phases:(1.1) - Initially, candidate functions are initializer list constructors (8.5.4) of a class
T
and the Argument List consists of an initializer list as one argument.
(1.2). If no viable initializer list constructor is found, overload resolution is performed again, where the Candidate Functions are all the constructors of the classT
and the argument list consists of the members of the initializer list.
vector
is a non-aggregate class that has two corresponding constructors:
explicit vector( size_type count ); // (3)
vector( std::initializer_list<T> init, // (7)
const Allocator& alloc = Allocator() );
Following the order described in [over.match.best], since (7) is a viable constructor candidate, we cannot specify (1.2) where (3) will be considered.
source to share