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

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

1

u/panoskj Dec 22 '23

where I can easily do so and {} for everything else (unless I slip into old habits and use ()

Or unless you want to initialize a std::vector calling the constructor with the size parameter or something like that. We are back to square one.

1

u/serviscope_minor Dec 22 '23

Ha! Yes, not a high point of C++ to be sure!