gpt4 book ai didi

c++ - unique_ptr、make_unique 和多态性

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:25 26 4
gpt4 key购买 nike

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 鼓励它可能是有风险的。)

关于c++ - unique_ptr、make_unique 和多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28996161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com