c++ - Base class unique_ptr to derived class shared_ptr -


i have base class passing unique_ptr reference function , want copy/move derived class shared_ptr (or unique_ptr want guarantee no memory leaked throughout execution).

i doing this:

std::shared_ptr<derived> f(unique_ptr<base>& b_ptr){      std::shared_ptr<derived> d_ptr= std::make_shared<base>(std::move(b_ptr));     return d_ptr; } 

this have, know not right way, know how this.

you almost correct.

std::make_shared creates new object, using perfect forwarding, unless there constructor taking std::unique_ptr&, thats not want.

in order this, need std::shared_ptr's constructor std::unique_ptr use std::static_pointer_cast function:

#include <memory> #include <iostream>  class parent{ virtual ~parent(); };  class derived : public parent { };  std::shared_ptr<derived> f(std::unique_ptr<parent>&& b_ptr) {     auto shared_base = std::shared_ptr < parent > {std::move(b_ptr)};      return std::static_pointer_cast<derived>(shared_base); } 

also, found idea pass b_ptr rvalue-ref because way user has explcitly use std::move(...) on object illustrate won't have ownership on unique_ptr anymore.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -