std :: make_unique和std :: unique_ptr与new之间的区别 [英] Differences between std::make_unique and std::unique_ptr with new

查看:192
本文介绍了std :: make_unique和std :: unique_ptr与new之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std :: make_unique 是否具有像 std :: make_shared 这样的效率优势?



与手动构造 std :: unique_ptr

相比,

  std :: make_unique< int>(1); // vs 
std :: unique_ptr< int>(new int(1));


解决方案

make_unique 主要有两个方面:




  • make_unique 对于创建临时文件是安全的,而显式使用 new 则必须记住有关不使用未命名临时文件的规则。

      foo(make_unique< T>(),make_unique< U>()); //例外安全

    foo(unique_ptr< T>(new T()),unique_ptr< U>(new U())); //不安全*


  • 加上 make_unique 最终意味着我们可以告诉人们不要使用 new ,而不是以前的规则不要使用 new ,但当您创建 unique_ptr 时除外。




还有第三个原因:




  • make_unique 不需要多余的类型用法。 unique_ptr< T>(新T())-> make_unique< T>()



没有一个原因涉及使用 make_shared 来提高运行时效率(由于避免了第二次分配) ,但可能会增加峰值内存使用量。)



*预计C ++ 17将包含规则更改,这意味着这不再是不安全的。参见C ++委员会论文 P0400R0 P0145R3 。。 p>

Does std::make_unique have any efficiency benefits like std::make_shared?

Compared to manually constructing std::unique_ptr:

std::make_unique<int>(1);         // vs
std::unique_ptr<int>(new int(1));

解决方案

The motivation behind make_unique is primarily two-fold:

  • make_unique is safe for creating temporaries, whereas with explicit use of new you have to remember the rule about not using unnamed temporaries.

    foo(make_unique<T>(), make_unique<U>()); // exception safe
    
    foo(unique_ptr<T>(new T()), unique_ptr<U>(new U())); // unsafe*
    

  • The addition of make_unique finally means we can tell people to 'never' use new rather than the previous rule to "'never' use new except when you make a unique_ptr".

There's also a third reason:

  • make_unique does not require redundant type usage. unique_ptr<T>(new T()) -> make_unique<T>()

None of the reasons involve improving runtime efficiency the way using make_shared does (due to avoiding a second allocation, at the cost of potentially higher peak memory usage).

* It is expected that C++17 will include a rule change that means that this is no longer unsafe. See C++ committee papers P0400R0 and P0145R3.

这篇关于std :: make_unique和std :: unique_ptr与new之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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