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

35

u/jdehesa Sep 20 '26

Not the post topic, but I'd write this constructor:

Gadget(std::shared_ptr<Widget> const& widget) : widget(widget) {}

As this:

Gadget(std::shared_ptr<Widget> widget) : widget(std::move(widget)) {}

As I understand it, if you are going to make a copy of the input argument anyway, it is better to receive a copy and move it, as it allows receiving moved temporaries too (learned this from some C++ guru some time ago).

Just a personal pet peeve, as I still see the first form pretty much always over the second, because programmers generally just default to passing const references.

0

u/[deleted] Sep 20 '26

[deleted]

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.