Std :: move into static_pointer_cast: Why doesn't static_pointer_cast have rvalue reference overload?

Suppose we have a fuction that expects a generic pointer by value. (In the real-life example, I take it from the rvalue link and forward it to the member.)

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

But we only have a generic 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));

Is the first task (building ptr from a temporary one) a triggering atomic increment and decrementing the reference count or moving a common pointer? (Note that he throws up.)

Inside static_pointer_castthere is an atomic increment of the reference counter. If we no longer need ptr, we would like to move it to f. But since overloading static_pointer_castusing the rvalue link will have no effect:

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

We still have an atomic increment and a corresponding atomic decrement as soon as it is ptrdestroyed. Why is there no such overload?

+6
source share
1 answer

I can answer the first part of your question, but not the second. Although I am not sure that this is provided by the standard, I am sure that:

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

refcounter /. -, , , ptr. , , , , . , , (http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr):

template< class Y > 
shared_ptr( shared_ptr<Y>&& r );

:

- shared_ptr r. * r, r null. , Y * T *

Y Derived, T - Base, Y* T*, . , , 2, 1. , , , , .

+3

Source: https://habr.com/ru/post/1016969/


All Articles