Search code examples
c++type-conversionshared-ptr

Converting sharet_ptr<Derived> to shared_ptr<Base>


I have a

class A: public std::enable_shared_from_this<A>{....}

class B: public A{....}

later in code, I'm doing this:

std::shared_ptr<A> Construct(....){
    class_field=std::make_shared<B>(...);
    
    return class_field->shared_from_this();
}

With this code, I want to make sure that the object of B gets destroyed once current class is destroyed, as well as when the object in client function goes out of scope.

Is this correct way to handle this? Is there a better way to get shared_ptr from shared_ptr?


Solution

  • Purpose of shared_from_this is to have access to shared pointer from class itself.

    You should not use this outside of class, so as a result your code in question is simply an overkill. it should be:

    std::shared_ptr<A> Construct(....){
        return std::make_shared<B>(...);
    }