mercredi 3 mai 2017

std::move into static_pointer_cast

Suppose we have a fuction expecting a shared pointer by value. (In a real life example I take it by rvalue reference and forward it to a member.)

void f(std::shared_ptr<Derived> ptr) { ... }

But we only have a shared pointer to the base class, so we use static_pointer_cast:

std::shared_ptr<Base> ptr = std::make_shared<Derived>();
f(std::static_pointer_cast<Derived>(ptr));

Does the first assignment trigger an atomic increment and decrement of the reference count or is the shared pointer moved? (Note that it's being up-casted.)

Within the static_pointer_cast there is an atomic increment of the reference count. In case we don't need ptr anymore, we'd want to move it into f. But as there is no overload of static_pointer_cast taking an rvalue reference, the move won't have any effect:

f(std::static_pointer_cast<Derived>(std::move(ptr)));

We still have the atomic increment and the corresponding atomic decrement as soon as ptr is destructed. Why is there no such overload?

Aucun commentaire:

Enregistrer un commentaire