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?
source share