c++inheritancesmart-pointers

Copying shared_ptr passed to base class


So I have a small hierarchy of classes and I need to pass down a shared_ptr to the base class that accepts a rvalue. However, in one of the cases I'd like to grab the shared_ptr for use in one of the derived classes.

My problem reduces to this:

https://godbolt.org/z/Kvaa7o1Gn

class Base {
  public:
    Base(std::shared_ptr<int>&& p)
        : a_{p}
    {
    }

  private:
    std::shared_ptr<int> a_;
};

class Derived : public Base {
  public:
    Derived(std::shared_ptr<int> p)
        : Base(copy_shared_ptr(p)) // this is of course not permitted, but I'd like to do something like this
    {
    }

  private:
    std::shared_ptr<int> copy_shared_ptr(std::shared_ptr<int> p)
    {
        p_ = p; // segfaults
        std::cout << "Now p_ is " << p_.use_count() << std::endl;
        return p_;
    }

    std::shared_ptr<int> p_;
};

int main() { Derived d{std::make_shared<int>(5)}; }

It is not possible to grab the shared_ptr before moving it on, since I need to construct my base class before I can initialize it. IS there anyway obvious idiom for achieving this that I might have missed?


Solution

  • You can pass a copy to Base then store the original in p_

    Derived(std::shared_ptr<int> p)
            : Base({p}), p_(std::move(p))
        {
        }