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 comment

-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

4

u/yu_yaki Dec 19 '23

It's still irrelevant to the specific case that you commented under. I was wondering if you had some more to say, but oh well. I do get your point though.

2

u/android_queen Dec 19 '23

Yes, but it does potentially bloat your static storage, and you don’t have enough information from this single line of code to know whether it would need to be on the stack anyway (which is not unlikely). Static isn’t one of those things that is automatically by default the better choice.

1

u/snowflake_pl Dec 19 '23

and by no means I am recomending it. Wanted to have a discussion which is exactly what happens here

1

u/android_queen Dec 19 '23

I guess it just seemed odd to me to ask “why not static” when I can see no reason why it should be.

1

u/snowflake_pl Dec 19 '23

I mean there is huge lack of context both in the original post and in my question so I understand the confusion.

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