Yes, if you move the shared pointer into the function, then:
the original sourcePtr
will become null, and
the reference count does not get modified.
If you know that you will no longer need the value of sourcePtr
after the function call, moving it into the function is a slight optimisation, as it saves an atomic increment (and later decrement, when sourcePtr
goes out of scope).
However, be careful that the identifier sourcePtr
is still valid for the rest of the scope, just that it holds a null pointer. Which means the compiler will not complain if you use it after the move, but if you forget it was moved from, you'll in all likelihood dereference the null. I tend to use this "optimising" move
a lot, and I've also been bitten by it a few times: more functionality is added to the function, and if you forget to undo the move
, you get a nice crash.
So moving when you no longer need it is a slight optimisation coupled with a slight maintenance burden. It's up to you to weigh which is more important in your case.
The above assumes that there is code which actually uses sourcePtr
between its declaration and the final call to foo
(thanks to @WhozCraig for pointing it out). If there is not, you'd be much better off creating the pointer right at the call site:
foo(std::make_shared<X>(...));
This way, you save the same amount of atomic operations, and you don't have a potentially dangerous empty shared pointer lying around.