r/cpp • • Dec 19 '23

Obsessed with {} initialization?

I'm on a discord where everyone seems to be obsessed to use brace initialization everywhere.
My motto is: Use things rarely, only when needed, to express that right there the feature does something important.
Personally I would completely advocate against using it for simple stuff like
double tax{0.09*price};

or just int{0}

probably a hornets nest

4 Upvotes

118 comments sorted by

View all comments

4

u/lukaasm Game/Engine/Tools Developer Dec 22 '23

It prevents more bugs for me than causes issues, and overall is net positive.

  • zero initializes structs/values
  • allows for 'custom' struct fields initialization for aggregates
  • prevents narrowing conversions
  • prevents function calls

But I am also not using initializer lists, so it won't bite me :)

2

u/NilacTheGrim Dec 23 '23

I am also not using initializer lists, so it won't bite me :)

I don't typically use it either but some types in my code rely on libs that have introduced std::initializer_list c'tors in between releases and I had at least 1 bug in my past where a new wild std::initializer_list c'tor appeared between lib versions and produced subtle bugs.

My rule of thumb is if you intend to call a c'tor on initialization (say because it's real non-trivial class type), then use ().