C++ 唯一的\u ptr,使\u唯一且多态
如果它的设计类似于:C++ 唯一的\u ptr,使\u唯一且多态,c++,C++,如果它的设计类似于: 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 ques
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
}
模板
唯一\u ptr使\u唯一(ArgT…args)
{
返回唯一的\U ptr(新的U(参数…);
//也许应该转发参数,这对这个问题并不重要
}
这样你就可以用它来创建派生对象了有人知道不这样做背后的原因吗?
因为这没有意义,你可以在调用它之后进行转换
std::unique_ptr<T> p = std::make_unique<U>(args);
std::unique_ptr p=std::make_unique(args);
因此,如果有一个函数接受std::unique\u ptr
,您仍然可以这样做
func(std::make_unique<U>(args));
func(std::make_unique(args));
对于您的实例,您可以只执行以下操作:
the_list.push_back( make_unique<Child>(1) );
将_列表向后推(使_唯一(1));
你的建议有什么好处?这就像是无缘无故的打字
(另外,一般来说,这是不安全的,因为它假设基类有一个虚拟析构函数,所以在转换
unique\u ptr
对象时需要小心,因此使用make\u unique
来鼓励它可能是有风险的。)如果仔细查看其定义,您会发现std::unique\u ptr可以从派生对象移动到基类。参考你能演示一下这是如何工作的,以及它如何比正常工作更好吗?它会像这样工作,重点是永远不要键入new
@tadmanauto=make_unique()
创建Foo
的实例并返回unique\u ptr
。不知道它们是无声转换的。如果U*
隐式转换为T*
,并且E
隐式转换为D