Reputation: 335
I have a base class which I am passing with unique_ptr as a reference to a function and I want to copy/move it to a derived class shared_ptr (or unique_ptr what I want it is too guarantee no memory leaked throughout the execution).
I am 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 is what I would like to have, but I know that this is not the right way, I would like to know how could I do something like this.
Upvotes: 1
Views: 1049
Reputation: 2271
You are almost correct.
std::make_shared
always creates a new object, using perfect forwarding, so unless there is a constructor taking a std::unique_ptr&
, thats not what you want.
In order to do this, all you need is the std::shared_ptr
's constructor from a std::unique_ptr
then use the 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, i found it a good idea to pass b_ptr
by rvalue-ref because that way the user has the explcitly use std::move(...) on their object just to illustrate that they won't have ownership over the unique_ptr
anymore.
Upvotes: 1