r/cpp • • Sep 20 '26

Magic statics vs. std::call_once

https://devblogs.microsoft.com/oldnewthing/20260916-00/?p=112703
73 Upvotes

11 comments sorted by

View all comments

Show parent comment

13

u/Low-Ad-4390 Sep 20 '26

If the original shared pointer is lvalue, then it will be copied into the constructor. If it’s an rvalue, it’ll be moved. So the worst case scenario - copy and move, the best case scenario - two moves or even move elision. If passed by const reference, it’s always a copy.

6

u/tokemura Sep 20 '26

More details in Scott Meyers - Effective Modern C++ Item 41: Consider pass by value for copyable parameters that are cheap to move and always copied.

0

u/[deleted] Sep 20 '26

[deleted] — view deleted comment

1

u/Low-Ad-4390 Sep 20 '26

So you are describing your experience, biased by the specifics of your codebase, couple it with assumptions of shared_ptr’s moves and destructors not being inlined and the cost of the empty shared_ptr’s destructor. The answer to your ”I dunno man, I just don’t see it” is “measure and decide”.
Another point worth considering here is - why do you pass a shared_ptr to a function in the first place?
If it’s just to read the pointed value, the just pass a reference to the underlying value. If you’re sharing the ownership, then why is the call chain deep?

0

u/[deleted] Sep 20 '26

[deleted] — view deleted comment

1

u/Low-Ad-4390 Sep 21 '26

You’ve been provided with an answer. What in it does not make sense for you? Your ui and data looks like a lot of shared pointers? What do you mean? This seems like a messed up ownership strategy.

-1

u/PossibilityUsual6262 Sep 20 '26

So from my perspective, the code bases i work with, You most likely getting that shared passed 4 call stacks or even more as a const ref, most of them cannot be inlined, from some member variable of some owner system.

I'm looking at it as - your best scenario is you move elision within inlined constructor, and worst scenario is if across some dll boundaries (comes up a lot in my work) you get two copies of shared ptr which ranges from extremely expensive to just expensive, depending if it is thread safe ptr or not.

Like im not seeing what is gained ever if you pass it by value instead of const ref by default. Is the other resources actually say what is the profit? Because to me so far it looks like one more "free abstraction" of modern cpp, and they are not free on average.

Even this one, if moved but not completely inlined, you would get destructor call of shared ptr, so we back to gambling again with "compiler smart enough to see that i moved ptr into variable, control block ref count wasn't ++ so destructor doesn't need to be called".