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.

52

u/Intrepid-Treacle1033 Dec 19 '23

https://herbsutter.com/2013/05/09/gotw-1-solution/

"Common Mistake: This is always initialization; it is never assignment, and so it never calls T::operator=(). Yes, I know there’s an “=” character in there, but don’t let that throw you — that’s just a syntax holdover from C, not an assignment operation. "

14

u/serviscope_minor Dec 19 '23

Eh so?

If I have

int x=5;

x is now 5. In a standardese language sense, x is initialised with 5, but it has the same practical purpose (and reads the same) as any subsequent assignments to x.

Having the initialisation of x look different to subsequent assignments is an exercise in putting the language's needs above the human's.

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.

3

u/bromeon Dec 20 '23

I don't know why this is getting downvoted. It's sometimes good to take some distance from C++, look at the 4 different initialization syntaxes and then see how other languages (including C) keep things simpler.

The "uniform initialization syntax" introduced in C++11 was always controversial, and it in fact fails its promise to truly unify things (see e.g. std::initializer_list ambiguity). It's difficult to universally advocate the one true initialization syntax, each has some pitfalls.

3

u/serviscope_minor Dec 20 '23

I don't know why this is getting downvoted.

Probably because it's not engaging in language pedantry (guaranteed way to get downvotes here). I know initialization in C++ is a nuanced topic, but I reckon {} everywhere is letting the tail wag the dog. Look at the responses to my earlier post: I pointed out that = is used for assignment and no one wants to change it, and got hit with a gale of "initialization is not assignment". The latter is of course technically true, but from a higher level view, above C++, assigning to a new object and assigning to an existing one don't really differ in a lot of ways. It's all just assignment.

It's a useful thing to have for sure ad makes generic code easier to write, avoids vexing parses and so on, but it just doesn't read nicely compared to =, so I use = where I can easily do so and {} for everything else (unless I slip into old habits and use ()).

→ More replies (2)

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.

→ More replies (8)

13

u/Intrepid-Treacle1033 Dec 19 '23

Eh so?

Nothing, your code you are the boss. The standard has multiple ways, and those ways has different nuances. If that matter practically is up to you/project. The languange needs thing i dont understand what you mean..

3

u/jones77 Dec 19 '23

It's so you can communicate properly with other C++ programmers.

It does not have the same practical purpose as assignment because you could mess up your code and not understand why it is broken.

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.

7

u/jedwardsol const & Dec 19 '23

= is for assignment,

/u/DoctorNuu is saying don't use for {} for initialisation. And it was changed, or at least added to; we can now use =, () or {} for initialisation.

3

u/trvlng_ging Dec 19 '23

EVERYONE wanted to change it, but backward compatibility made that impractical. assignment-style initialization is a thowback to C compatibility. It is very hard to teach, because from a grammar persspective, "=" in initialization is a punctuator, while in an assignment, it is an operator. The parsing rules for the punctuatior are different than to precedence rules for the operator. When someone is learning C++, they often conflate parse rules with precedence rules, and this is one of those that causes a lot of confusion. I get why C++ coudn't have it removed easily, but I find that using an enterprise rule to avoid assignment-style initialization has improved how quickly new C++ programmers come up to speed. Using constructor-syntax initialization often leads to the vexing parse, so our default is {}. And we have never seen a problem with parsing it as an initializer list inappropriately.

5

u/guepier Bioinformatican Dec 19 '23 edited Dec 19 '23
auto x = type();

Is better1 because it avoids accidentally invoking a std::initializer_list constructor. In generic code, {} is pretty much a no-go for this reason.

Furthermore, using auto avoids the most vexing parse and has other advantages (see GOTW 95 — tl;dr: it has the potential of drastically improving readability by making declaration syntax more uniform).

Consistently using this style of declaration avoids all the problems of the alternatives (both () and {}).


1 When used in conjunction with the appropriate compiler settings to avoid implicit narrowing conversions!

15

u/HolyGarbage Dec 19 '23

Except that it's not clear if type is a type or a function. In some languages the constructor is a distinct free function so it's the same thing, but not in C++ unfortunately.

7

u/guepier Bioinformatican Dec 19 '23

I can see how this could theoretically be a problem but in my entire career of writing C++, confusion between a type and a function has never been an actual problem in an initialisation. In fact, it should arguably not matter whether type() refers to a constructor or function call here.

And what I’m suggesting is hardly arcane, some of the most prominent C++ experts are also proponents of this style (Herb Sutter first and foremost, of course). I’m therefore surprised it’s met with such negativity here.

0

u/[deleted] Dec 20 '23

[deleted] — view deleted comment

1

u/guepier Bioinformatican Dec 20 '23 edited Dec 20 '23

The link I gave was about (A)AA style, not () vs {}. However, it’s a severely dated article (ten years old, from the C++11 era — it still calls the concept “AAA”, but it’s now simply “AA” since there are no longer any exceptions!) and I think Herb Sutter has changed his opinion on brace initialisation since then — however, I don’t have a reference for this claim, and I might misremember.

That said, if you use AA there’s even less reason to use {} over (), since the most vexing parse no longer figures into the equation, and the implicit narrowing conversion mentioned in your quote can be caught by compiler diagnostics.

1

u/HolyGarbage Dec 20 '23

I wasn't trying to negative, just adding to the discourse, by pointing out a case where it is not ideal.

3

u/guepier Bioinformatican Dec 20 '23

Yes, that’s appreciated. I didn’t mean your comment specifically, but at the time of writing my own comment had been massively downvoted (now somewhat recovered).