为什么C ++ 11有`make_shared`而不是`make_unique` [英] Why does C++11 have `make_shared` but not `make_unique`

查看:463
本文介绍了为什么C ++ 11有`make_shared`而不是`make_unique`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

make_unique和完美转发

为什么C ++ 11有 make_shared 模板,但不是 make_unique 模板?

Why does C++11 have a make_shared template, but not a make_unique template?

这使代码非常不一致。

auto x = make_shared<string>("abc");
auto y = unique_ptr<string>(new string("abc"));


推荐答案

根据Herb Sutter的本文是部分疏忽。这篇文章包含了一个很好的实现,并强调使用它:

According to Herb Sutter in this article it was "partly an oversight". The article contains a nice implementation, and makes a strong case for using it:

template<typename T, typename ...Args>
std::unique_ptr<T> make_unique( Args&& ...args )
{
    return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
}

更新:原始更新已更新,重点已更改。

Update: The original update has been updated and the emphasis has changed.

这篇关于为什么C ++ 11有`make_shared`而不是`make_unique`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆