[英]What is the correct way to convert a std::unique_ptr to a std::unique_ptr to a superclass?
假設我有一個名為foo
的類,該類繼承自名為bar
的類。
我有一個std::unique_ptr
到foo
的實例,我想將其傳遞給只需要std::unique_ptr<bar>
的函數。 如何轉換指針使其在函數中起作用?
您可以將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
析構函數。
由於繼承,因此不需要任何特殊要求。 您需要使用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));
}
您可以使用以下語法:
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 。
您不能這樣做,因為它會違反最基本的unique_ptr
規則:必須只有一個實例擁有給定的指針,並且unique_ptr
擁有它的完全所有權(當它超出范圍時,pointe被刪除)。
如您所見, unique_ptr<T>
和unique_ptr<U>
(其中U : T
)不兼容。
對於shared_ptr
,您可以為其具有多個實例,存在std::static_pointer_cast
行為與static_cast
相似,不同之處在於它接受shared_ptr
並返回另一個(並且都指向同一個對象)。
如果您絕對需要使用unique_ptr
,則必須創建一個函數,該函數首先放棄當前的unique_ptr
然后將該指針放入正確類型的新指針中。 函數調用之后,您可能還需要執行相反的轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.