I was reading the C++0x faq and came across the section detailing initializer lists. The examples were mostly variations of:
vector vi = { 1, 2,
The ({1, 2, 3})
form calls the constructors of vector
directly, and passes as first argument a {1, 2, 3}
. You could have passed more arguments
vector vk({1, 2, 3}, myAllocator);
If vector
would not have a constructor whose first parameter is an initializer_list
or of another type that could be initialized by {1, 2, 3}
(like, another container class), it would not work. In your case it works because vector
in fact has a constructor whose first parameter is a initializer_list
. This is just like in normal function calls
void f(vector const& vk);
int main() { f({1, 2, 3}); }
If you omit the parentheses, as in vector
, the exact meaning depends on the class. A vector
has an initializer list constructor, which is a constructor with a first parameter of type initializer_list
(optionally a reference to it), and all other params with default arguments. If the class has such a constructor, then the initializer list is passed to that constructor. Alternatively the class could simply be an aggregate (like struct A { int a; int b; int c; };
, the initializer list would then init the members) or have a constructor that accepts 3
separate int
arguments.
Finally the = { 1, 2, 3 }
form is almost identical to the version omitting the parentheses (i.e just removing =
), except that it forbids to use explicit constructors (i.e had they declared it as explicit vector(initializer_list
or had they declared a explicit vector(int, int, int);
instead, it would result in an error if you use = { 1, 2, 3 }
).