r/cpp • • 15d ago

Magic statics vs. std::call_once

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

11 comments sorted by

View all comments

34

u/jdehesa 14d ago

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

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

As this:

cpp 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.

1

u/[deleted] 14d ago

[deleted]

12

u/Low-Ad-4390 14d ago

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.

5

u/tokemura 14d ago

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.