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

50

u/jedwardsol const & Dec 19 '23

What do you advocate using instead, and why is that better?

18

u/serviscope_minor Dec 19 '23

What do you advocate using instead

=

and why is that better?

There's a reason C++ uses = for assignment and no one wants to change it.

43

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting Dec 19 '23

There's a reason C++ uses = for assignment and no one wants to change it.

And that's exactly why {} should be preferred for initialization, because people still confuse assignment and initialization in 2023.

1

u/Pretend-Guide-8664 Dec 19 '23

I suppose you don't want me to ask what the difference is then...

Technically I think one writes to memory a new value (initialization), and the other either copies a value, copies a pointer, or moves data (assignment).

Is there a chart for the yes and nos of this?

4

u/joahw Dec 19 '23

That is correct. For objects if you accidentally do an assignment instead of initialization you are likely to do unnecessary copies, moves and/or destruction of temporaries which could have performance implications.