Is there any subtle difference between prepending '=' to initializer lists?
c++, c++11
Solution
1.
vector<double> v { 0.0, 1.1, 2.2, 3.3 };
Is a direct-list-initialization. It means that it is initialized with a constructor taking an initializer list.
Constructor :
vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
2.
vector<double> v = { 0.0, 1.1, 2.2, 3.3 };
Is a copy-list-initialization.
The standard is pretty clear :
8.5.4 List-initialization [dcl.init.list]
List-initialization is initialization of an object or reference from a braced-init-list. Such an initializer is called an initializer list, and the comma-separated initializer-clauses of the list are called the elements of the initializer list. An initializer list may be empty. List-initialization can occur in direct-initialization or copyinitialization contexts; list-initialization in a direct-initialization context is called direct-list-initialization and list-initialization in a copy-initialization context is called copy-list-initialization. [ Note: List-initialization can be used :
- as the initializer in a variable definition
[...]
Example :
std::complex<double> z{1,2};
[...]
std::map<std::string,int> anim = { {"bear",4}, {"cassowary",2}, {"tiger",7} };
For the difference between both, we should go a little bit further :
13.3.1.7 Initialization by list-initialization [over.match.list]
- For direct-list-initialization, the candidate functions are all the constructors of the class T.
- For copy-list-initialization, the candidate functions are all the constructors of T. However, if an `explicit` constructor is chosen, the initialization is ill-formed. [ Note: This restriction only applies if this initialization is part of the final result of overload resolution — end note ]
Problem
Is there any subtle difference between these two ways of initializing variables in C++11? `vector<double> v { 0.0, 1.1, 2.2, 3.3 };` `vector<double> v = { 0.0, 1.1, 2.2, 3.3 };` Can the latter be used for all the same cases as the first one? Stroustrup claims in TCPL4ED that the first way is the only one that can be used in every context, and thus recommends it. Later on, he seems to imply that the second one is just a different way of writing the first one.