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 comments

33

u/HolyGarbage Dec 19 '23 edited Dec 19 '23

It doesn't make a difference for integral types, but for classes, and in particular where copy and move constructors and assignment operators have user provided implementations it does make a difference.

If you're assigning where you meant to be initializing you could either a) assign to uninitialized memory which is potentially undefined behavior depending on the class definition, or b) first default constructing followed by an assignment which could incur additional performance costs.

Note, I'm not saying that using = for initialization in your example would do this, but was simply demonstrating the importance of the distinction between initialization and assignment, which using the = for initialization makes less clear. The feature of using braces for all kinds of initialization is called "uniform initialization" for a reason, to make it clear directly by the syntax what operation you're invoking.

1

u/serviscope_minor Dec 19 '23

It's not a high point to be sure. Uniform is, well, uniform in the language. The caveat is that it makes the code less nice to read, because you have two different syntaxes for a variable getting a value.

2

u/HolyGarbage Dec 20 '23

you have two different syntaxes for a variable getting a value.

That's exactly the point. Because assignment and initialization is not the same thing.

1

u/serviscope_minor Dec 20 '23

And my point is that's putting the needs of the language ahead of the programmer.

People like = for assignment and initialization is from a higher level perspective than C++ a kind of assignment.

3

u/HolyGarbage Dec 20 '23

No it's not. Both initialization and assignment are things the programmer should be aware of. = is already used for assignment in C++, your example however used = for initialization, not assignment. I'm saying that can be confusing since it looks like an assignment.

1

u/serviscope_minor Dec 20 '23

I think we are taking at crossed purposes. I understand the grammar. I mean the assignment/initializing thing is specific to C++ not a general thing about programming.

= reads better and is (when it works) more regular since = sets values in any context.

→ More replies (0)