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?

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.

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).