r/cpp • • Mar 01 '21

"Simple" C++ Initialization Flowchart

http://randomcat.org/cpp_initialization/initialization.png
204 Upvotes

65 comments sorted by

View all comments

103

u/atimholt Mar 01 '21

25

u/piglett23 Mar 01 '21

Wow, I recently started a position developing safety-critical software and that really clears up why we use brace-initialization. It seems to just work for most things. Thanks for that!

49

u/FriendlyRollOfSushi Mar 01 '21 edited Mar 02 '21

Never once I've seen the trust towards the committee fall as low as it did when people in my company started to migrate to C++11 and realized that this is their life now. Haven't recovered since, to be honest.

The example is de-obfuscated, obviously: it's usually an issue somewhere deep, sometimes in templated code where you don't even know what the types are just by looking at the code. In a large enough company with enough people coming and leaving and a moderately relaxed review process, you are pretty much guaranteed to have a steady flow of bugs like this. It's a footgun with infinite ammo.

I sort of understand why this happened, but it feels like we as a community completely failed to do things right for once, so that we could stop teaching all other initialization methods to people and pretend that the () syntax doesn't exist and shouldn't be used anymore.

Now I see mixed-style initialization lists all the time (see the bonus part from the link above), and cry internally from time to time while thinking about this whole situation.

Sigh...

1

u/infectedapricot Mar 02 '21 edited Mar 02 '21

Part of the problem with that particular case lies with std::vector. That particular function should've been a static method rather than a constructor:

auto v = std::vector<int>::make_n_of(n);

(No doubt there's a better name than that.) Edit: But of course that wouldn't have been possible when vector was originally created, because there were no move constructors or guaranteed copy elisions.

3

u/FriendlyRollOfSushi Mar 02 '21

That would make some other people unhappy. If your code is full of numeric vectors, and barely has any initializer lists, it would feel like you are paying usability taxes for someone else.

Personally, I like tagged ctors as a compromise: imagine if we could write vec1_{std::construct, size}, vec2_{std::reserve, size}, etc.

Unfortunately, tags introduce a small runtime penalty when not inlined. I wish we had zero-cost discriminating tags.

6

u/Nobody_1707 Mar 02 '21

Differentiating constructors is the killer application of named arguments in the languages I've used that have had them.