7

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?

4

4 回答 4

27

您可以将std::unique_ptr<foo>右值转换为std::unique_ptr<bar>

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

显然,指针将由拥有b,如果b被销毁bar需要有一个virtual析构函数。

于 2013-08-23T00:49:30.447 回答
2

由于继承,没有什么特别的要求。您需要使用std::move将 unique_ptr 传递给函数,但即使类型匹配也是如此:

#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));
}
于 2013-08-23T12:53:57.497 回答
0

您可以使用以下语法:

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

或者您可以使用std::move.

另一种选择是发出原始指针,但您需要更改一个函数:

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

这是一篇关于智能指针并将其传递给函数的好文章:http: //herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters

于 2013-08-23T00:51:44.577 回答
-1

你不能,因为它违反了最基本的unique_ptr规则:必须只有一个实例持有一个给定的指针,并且拥有它的unique_ptr完全所有权(当它超出范围时,指针被删除)。

unique_ptr<T>unique_ptr<U>(where U : T) 不兼容,如您所见。

For shared_ptr,你可以有多个实例,它的std::static_pointer_cast行为就像 a static_cast,除了它接受 ashared_ptr并返回另一个(并且都指向同一个对象)。

如果您绝对需要使用 a unique_ptr,则必须创建一个函数,该函数首先放弃您的当前unique_ptr并将该指针放入正确类型的新指针中。您可能还需要在函数调用后进行相反的转换。

于 2013-08-23T00:46:13.757 回答