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

-16

u/snowflake_pl Dec 19 '23

Why not static constexpr? 🙂

15

u/yu_yaki Dec 19 '23

because price might not be constexpr? Why static though?

-9

u/snowflake_pl Dec 19 '23

Maybe static doesn't make a difference for a small variable but was it large, giving it static storage ensures compile time initialization and prevents unnecessarily copying the data to stack

3

u/_curious_george__ Dec 19 '23

Doesn’t necessarily make sense in practice.

Static storage is going to pollute the cache. Which will often be far worse than copying some trivial variable to the stack.

0

u/snowflake_pl Dec 19 '23

For optimized builds and trivial types static and automatic will be equivalent with variables completely compiled out. For bigger entities you are right, cache miss will most likely be more pricy than copy to stack. There is a threshold where copy becomes worse than cache miss but it's pretty much impossible to determine without precise measurements and even then the result will be tied to hw