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

1

u/jdehesa Sep 20 '26 edited Sep 20 '26

EDIT: Original explanation below is wrong. Const references do not create a copy of temporary r-values. The difference between the two is that passing the argument by copy make it possible to create no copies at all (only moves) if you pass a r-value, whereas in the original code, since the const reference can never be moved, you can never avoid the one copy you need to make.

Original wrong comment:
In many cases, both construct one new shared pointer - in the first case with a copy constructor to initialize the member variable, in the second case when you pass the value by copy (the member variable is initialized with a move constructor, so not a copy). As others mentioned, the second form still creates one single copy if the argument is a r-value, whereas the first one will create an extra intermediate copy so it can be passed as a const reference (or that's how I understand it, check authoritative sources for details).