如果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
}以便您可以使用它来创建派生对象?
有人知道不这么做背后的理性吗?
发布于 2015-03-11 20:02:13
因为没有意义,所以无论如何都可以在调用它之后进行转换。
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可能是有风险的。)
发布于 2019-09-09 01:38:26
如果您查看派生的std::unique_ptr的定义,您会发现它可以从派生的迁移到基的。请参阅https://stackoverflow.com/a/57797286/3758879
https://stackoverflow.com/questions/28996161
复制相似问题