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
}
Run Code Online (Sandbox Code Playgroud)
这样你就可以用它来创建派生对象了吗?
谁知道不这样做的理性背后?
因为没有意义,所以无论如何都可以在调用之后进行转换.
std::unique_ptr<T> p = std::make_unique<U>(args);
Run Code Online (Sandbox Code Playgroud)
所以,如果有一个功能,std::unique_ptr<T>你仍然可以做
func(std::make_unique<U>(args));
Run Code Online (Sandbox Code Playgroud)
对于您的实例,您可以这样做:
the_list.push_back( make_unique<Child>(1) );
Run Code Online (Sandbox Code Playgroud)
你的建议有什么好处?它似乎无缘无故地打字.
(另外,一般来说这不安全,因为它假设基类有一个虚拟析构函数,你需要小心转换unique_ptr对象,所以有一个make_unique鼓励它可能有风险.)
| 归档时间: |
|
| 查看次数: |
2784 次 |
| 最近记录: |