Using std::move with std::shared_ptr

31,209

Yes, if you move the shared pointer into the function, then:

  1. the original sourcePtr will become null, and

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

Share:
31,209
ksl
Author by

ksl

Updated on April 15, 2020

Comments

  • ksl
    ksl about 4 years

    I have a function defined as follows:

    void foo(std::shared_ptr<X> x) { ... };
    

    If I declare a shared ptr to X:

    std::shared_ptr<X> sourcePtr(new X(...));
    

    I can then call foo as follows:

    foo(std::move(sourcePtr));
    

    or

    foo(sourcePtr);
    

    I understand that if I use the first option then sourcePtr becomes null. Does it also prevent the reference count from being incremented?

    If that doesn't matter, which option should I prefer? Should I be considering anything else when making such a decision?