sdgfsdh sdgfsdh - 1 year ago 60
C++ Question

Why would I std::move an std::shared_ptr?

I have been looking through the Clang source code and I found this snippet:

void CompilerInstance::setInvocation(
std::shared_ptr<CompilerInvocation> Value) {
Invocation = std::move(Value);
}


Why would I want to
std::move
an
std::shared_ptr
?

Is there any point transferring ownership on a shared resource?

Why wouldn't I just do this instead?

void CompilerInstance::setInvocation(
std::shared_ptr<CompilerInvocation> Value) {
Invocation = Value;
}

Answer Source

I think that the one thing that the other answer did not emphasize enough is the point of speed.

std::shared_ptr reference count is atomic. increasing or decreasing the reference count requires atomic increment or decrement. this is hundreds of times slower than non-atomic increment or decrement.

By moving the shared_ptr instead of copying it, we "steal" the atomic reference count and we nullify the other shared_ptr. "stealing" the reference count is not atomic, and it is hundred times faster than copying the shared_ptr (and cousing atomic reference increment or decrement).

Do note that this technique is used purely for optimization. copying it (as you suggested) is just as fine functionality-wise.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download