Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should we use parenthesis ( ) vs. initializer { } syntax to initialize objects in C++11? [duplicate]

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?

like image 823
Ajay yadav Avatar asked Feb 09 '16 07:02

Ajay yadav


1 Answers

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.

like image 58
Tristan Brindle Avatar answered Sep 25 '22 16:09

Tristan Brindle