r/cpp • • Jun 05 '18

Initialization in Modern C++

https://twitter.com/timur_audio/status/1004017362381795329
379 Upvotes

51 comments sorted by

View all comments

41

u/James20k P2005R0 Jun 06 '18

This is the main problem i found with the new decidedly not uniform initialisation syntax - it adds yet another way to initialise stuff that seems to only be appropriate in some situations with all sorts of little quirks to it that make it not universally applicable

As far as I can tell, its basically good for initialising container types like std::vector and map, and that's about it

I'm not a c++ expert by any stretch though so maybe i'm totally missing something

27

u/SoundOfOneHand Jun 06 '18

There are reasons to prefer brace initialization in general. The only place I’m aware of that it’s not always possible is that a std::initializer_list constructor is always preferred, so you need parens if there is ambiguity, and this can be tricky in a template.

Braced initialization prevents narrowing conversions so you get some additional type safety. It also prevents the most vexing parse. Of course you also get nice collection literals as you mentioned.

16

u/render787 Jun 06 '18

FWIW the style I've converged on is "use brace initialization in almost all cases, and avoid ever writing `std::initializer_list` constructors"

the braced initialization can be really nice in templates because it can also initialize the aggregates correctly in cases where paren initialization would fail (because using the parentheses initialization cannot become aggregate initialization IIUC)

2

u/youshouldnameit C++ dev Jun 06 '18

avoid ever writing `std::initializer_list` constructors

Could you allobrate on why its not a good idea to write those constructors for your own types?

14

u/redditsoaddicting Jun 06 '18

They're insanely greedy and often disallow you from using braces to call other constructors.

1

u/kalmoc Jun 06 '18

Why would you want to use braces to call other constructors in the first place? The only reason to write initializater_list constructors in the first place is usually because you want your type to behave like an array / container. If that is the case, then why would you expect my_array a{1,2} to do anything but fill a with the values 1,2?

2

u/redditsoaddicting Jun 06 '18

I was going along with the whole uniform initialization thing. I don't mind the braces if they're actually uniform, but they're not.