How can I use shared_from_this in a derived class without unnecessary RC manipulation?

If I want to create shared_ptr<Derived> in a member function of a derived class in a hierarchy that inherits from the base class, I can use shared_from_this and static_pointer_cast :

 class Base: public std::enable_shared_from_this<Base> { }; class Der: public Base { public: std::shared_ptr<Der> make_SP_to_Me () { return std::static_pointer_cast<Der>(shared_from_this()); } }; 

My concern is that static_pointer_cast accepts its argument lvalue-ref-to-const, so when a new shared_ptr<Der> , the reference count in the control block increases. When shared_ptr<Base> returned from shared_from_this is destroyed, the refcount in the control block will be reduced again. I was surprised to see that the static_pointer_cast overload does not have an rvalue value, which avoids the need to manipulate the refcount in the control unit.

shared_ptr<T> has a template constructor that accepts rvalues โ€‹โ€‹of type shared_ptr<U> , which executes moves, while avoiding the need to do recount operations. Is there any reason that static_pointer_cast not doing the same? And is there any way for me to write the above code that does not include unnecessary manipulations with recounts?

+6
source share
1 answer

It looks like you will have to rely on optimizing the return value and hope that it is smart enough to help you.

If std::*_pointer_cast had overloads that accept forwarding links ( T&& ), they could transfer ownership from temporary ones, and that would not be a problem. I consider this to be oversight in a C ++ 11 library.

+1
source

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


All Articles