簡體   English   中英

unique_ptr,make_unique和多態

[英]unique_ptr, make_unique and polymorphism

如果make_unique設計像這樣,將不會更加有用:

template< typename T, typename U=T, typename ...ArgT>
unique_ptr<T> make_unique( ArgT ...args )
{
    return unique_ptr<T>( new U(args...) );
    // maybe parameters should be forwarded, not really important for this question
}

這樣就可以用它來創建派生對象?
有人知道不這樣做的原因嗎?

由於沒有意義,因此您可以在調用后進行轉換。

std::unique_ptr<T> p = std::make_unique<U>(args);

因此,如果有一個采用std::unique_ptr<T>的函數,您仍然可以

func(std::make_unique<U>(args));

對於您的實時示例,您可以執行以下操作:

the_list.push_back( make_unique<Child>(1) );

您的建議有什么好處? 似乎無緣無故地輸入更多內容。

(此外,通常這是不安全的,因為它假定基類具有虛擬析構函數,因此在轉換unique_ptr對象時需要格外小心,因此使用make_unique鼓勵使用它可能會有風險。)

如果查看其定義,您會發現std :: unique_ptr可以從派生的移動到基數。 請參閱https://stackoverflow.com/a/57797286/3758879

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM