Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
    {
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading