Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to convert a std::unique_ptr to a std::unique_ptr to a superclass?

Tags:

c++

c++11

Suppose I have a class called foo which inherits from a class called bar.

I have a std::unique_ptr to an instance of foo and I want to pass it to a function that only takes std::unique_ptr<bar>. How can I convert the pointer so it works in my function?

like image 778
merlin2011 Avatar asked Aug 23 '13 00:08

merlin2011


2 Answers

You can convert a std::unique_ptr<foo> rvalue to an std::unique_ptr<bar>:

std::unique_ptr<foo> f(new foo);
std::unique_ptr<bar> b(std::move(f));

Obviously, the pointer will be owned by b and if b gets destroyed bar needs to have a virtual destructor.

like image 123
Dietmar Kühl Avatar answered Oct 17 '22 22:10

Dietmar Kühl


Nothing special is required because of the inheritance. You need to use std::move to pass the unique_ptr to a function, but this is true even if the types match:

#include <memory>

struct A {
};

struct B : A {
};

static void f(std::unique_ptr<A>)
{
}

int main(int,char**)
{
  std::unique_ptr<B> b_ptr(new B);
  f(std::move(b_ptr));
}
like image 45
Vaughn Cato Avatar answered Oct 17 '22 23:10

Vaughn Cato