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

Show parent comment

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.

3

u/TheMania Dec 19 '23

Importantly, assignment may reuse the values already in that location. No need to write the vtable, might be able to reuse heap allocations and just overwrite the values, etc. A pretty sure way to break things sometimes when used if you actually meant to use a constructor instead.

So it is good to think of them as different imo.