syntax question

hey, so there's 2 ways to declare a variable of class
first :
mystring ex("lol");
second :
mystring ex{"lol"};

which one is better ?
https://stackoverflow.com/questions/18222926/why-is-list-initialization-using-curly-braces-better-than-the-alternatives

edit: would also suggest Item 7: Distinguish b/w () and {} when creating objects from 'Effective Modern C++', Scott Meyers
Last edited on
thank you
One thing to keep in mind is that they are not always equivalent:
The most well-known example of this is probably the two-argument vector constructor (does Meyers mention this?):
1
2
std::vector<int> a{5, 10}; // two elements (5 and 10)
std::vector<int> b(5, 10); // five elements containing the value 10 

The behavior differs because only the first form creates an initializer_list.

This can lead to unexpected behavior. One example is std::whatever::emplace_back(). Consider the structure std::vector<std::vector<int>> v;

What does this do?
v.emplace_back(5, 10);

It turns out that the semantics actually depend on the allocator, which is unfortunate, but by default (i.e., when the allocator is std::allocator), the element is value-constructed (parentheses are used).
Last edited on
Topic archived. No new replies allowed.