Updated
I have gone through links (such as When to use the brace-enclosed initializer?) on when should I use use {}
brace initialization, but information is not given on when we should use parenthesis ( )
vs. initializer { }
syntax to initialize objects in C++11/14? What standard practices suggest to use ()
over {}
?
In rare cases, such as vector<int> v(10,20);
or auto v = vector<int>(10,20);
, the result is a std::vector
with 10 elements. If we uses braces, the result is a std::vector
with 2 elements. But it depends on the caller use case: either he/she want to allocate vector of 10 elements or 2 elements?
Scott Meyers tackles this issue in Item 7 of his fantastic "Effective Modern C++". He runs through the differences, pros and cons of both syntaxes, and concludes
There’s no consensus that either approach is better than the other, so my advice is to pick one and apply it consistently.
On the other hand, the C++ Core Guidelines suggest that you prefer the initialiser syntax, so perhaps that's the better default to go for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With