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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With