16

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?

Community
  • 1
  • 1
Ajay yadav
  • 4,141
  • 4
  • 31
  • 40

2 Answers2

13

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.

Tristan Brindle
  • 16,281
  • 4
  • 39
  • 82
  • 3
    Personally I tend to agree with Meyers on this one, but I also have to write code in many cases that has to build with older versions of Visual C++ that lack support for {} initializer lists. Like ``auto``, it's more often than not a matter of judgement where it improves vs. obscures readability. Still, if you are entirely new to C++, you are probably safer with the rules for {} initializers per the core guidelines. – Chuck Walbourn Feb 09 '16 at 07:24
11

Congratulations, you've just hit on the canonical example of why you should prefer braced initialization if your compiler supports.

If you want a std::vector of two elements, you use:

vector<int> v = { 10, 20 };

If you use vector<int> v(10,20); you are actually calling the constructor that takes two integer-convertible elements which is the signature explicit vector (size_type n, const value_type& val = value_type(), const allocator_type& alloc = allocator_type()); Remember that std::vector was added to the language in C++98 while braced-initialization didn't get added until C++11.

See the Core C++ Guidelines, specifically ES.23: Prefer the {} initializer syntax

smasher
  • 294
  • 2
  • 17
Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81
  • 10
    Any why is this an example of why one should *prefer* one over the other? To me, it looks more like an example where you don't actually have a choice. – juanchopanza Feb 09 '16 at 07:30
  • 1
    This is covered in a lot of details by Herb Sutter and Bjarne Stroustrup in the link to the Core C++ Guidelines. – Chuck Walbourn Sep 19 '16 at 22:27