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

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

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

+7
c ++ c ++ 11
source share
4 answers

You can convert the value of std::unique_ptr<foo> r to the value of std::unique_ptr<bar> :

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

Obviously, the pointer will belong to b , and if b is destroyed, then bar must have a virtual destructor.

+27
source share

Nothing much is required due to inheritance. You need to use std::move to pass the unique_ptr function to the 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)); } 
+2
source share

You can use this syntax:

 std::unique_ptr<parent> parentptr = std::unique_ptr<child>(childptr); 

Or you can use std::move .

Another option is to emit a raw pointer, but you need to change the function:

 void func(const parent* ptr) { // actions... } func(*childptr); 

Here is a good article on smart pointers and passing it to functions: http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters .

0
source share

You cannot, because this violates the most basic rule unique_ptr : there must be only one instance that contains the specified pointer, and unique_ptr has full ownership of it (when it goes beyond the scope, the tocher is deleted).

unique_ptr<T> and unique_ptr<U> (where U : T ) are incompatible, as you saw.

For shared_ptr , for which you can have multiple instances, there is std::static_pointer_cast , which behaves like a static_cast , except that it takes shared_ptr and returns another (and both point to the same object).

If you absolutely must use unique_ptr , you will need to create a function that first disables your current unique_ptr and puts this pointer in the new correct type. You may also need to do the inverse transformation after calling the function.

-one
source share

All Articles