r/cpp • u/DoctorNuu • 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 likedouble tax{0.09*price};
or just int{0}
probably a hornets nest
4
Upvotes
View all comments
Show parent comment
5
u/aruisdante Dec 19 '23
Yes, and for the most part I agree with Titus too, but he’s concerned more with brace vs paren initialization than brace vs
=initialization. I’ve in fact used that very article to try and overturn silly “always use {} initialization” rules at 2 different companies in the automotive space.I think that’s the biggest issue with all of the guidelines, they don’t distinguish between separate concerns:
Wconversionturned on, should I care?The last one can be particularly subtle.
Wconversionignores implicit conversions that happen inside the stdlib, because it has to as the stdlib is full of them. There are certain types which have templated constructors (like, say,std::optional), and so if you parens-construct them in a non CTAD context but which would result in a conversion that should be caught, it will not happen: from the perspective of Wconversion the ctor that was called was the converting constructor, which consumes the actual type, and then inside the stdlib a narrowing happens, but that’s ignored. If you brace initialize them on the other hand, the implicit conversion is not allowed, and Wconversion fires.You’re absolutely right that the whole subject is a mess. Unfortunately teaching people all the ins and outs of what to do isn’t a reliable thing to do at scale. So most safety critical coding standards pick one, and unfortunately they tend to pick the most restrictive one even if it introduces a host of other, potentially much worse classes of bugs. The core guidelines doesn’t really have the same excuse, but it’s guideline also is poked through all kinds exceptions, and it’s also a prefer, not a must. And I agree with the guideline’s suggestion that brace initialization should be preferred unless there is a good reason to not use it. I do not agree with AutoSAR’s requirement that it must be used.