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

Update

I used references (for example, When to use an initializer enclosed in brackets? ), When should I use initialization {} , but information is not specified, when should we use syntax ( ) against initialization { } to initialize objects in C ++ 11/14 ? What standard methods suggest using () over {} ?

In rare cases, such as vector<int> v(10,20); or auto v = vector<int>(10,20); , the result is std::vector with 10 elements. If we use curly braces, the result will be std::vector with two elements. But it depends on the use case of the caller: either he wants to highlight a vector of 10 elements, or 2 elements?

+5
source share
2 answers

Scott Myers solves this problem in paragraph 7 of his fantastic "Effective Modern C ++". It runs through the differences, pros and cons of both syntaxes and concludes

There is no consensus that any approach is better than the other, so my advice is to choose one and apply it consistently.

On the other hand, the basic principles of C ++ suggest that you prefer the initializer syntax , so this may be the best default option.

+7
source

Congratulations, you just came across a canonical example of why you should prefer force initialization if your compiler supports it.

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

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

If you use vector<int> v(10,20); , you are actually a constructor that accepts two integer convertible elements that are 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 in braced-initialization mode it is added before C ++ 11.

See Basic C ++ recommendations , in particular ES.23: Prefer {} initiator syntax

+2
source

Source: https://habr.com/ru/post/1242592/


All Articles