简体   繁体   中英

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

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?

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.

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));
}

You may use this syntax:

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

Or you may use std::move .

The other option is to emit raw pointer, but you need to change a function:

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

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

You can't, because it would violate the most basic unique_ptr rule: there has to be only one instance that holds a given pointer, and the unique_ptr has full ownership of it (when it goes out of scope, the pointee is deleted).

unique_ptr<T> and unique_ptr<U> (where U : T ) aren't compatible, as you've seen.

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

If you absolutely need to use a unique_ptr , you'll have to create a function that first disowns your current unique_ptr and puts that pointer into a new one of the right type. You might also need to do the opposite conversion after your function call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM