与新运算符相比,使用std :: make_unique的优点 [英] Advantages of using std::make_unique over new operator

查看:358
本文介绍了与新运算符相比,使用std :: make_unique的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相对于 new 运算符,使用 std :: make_unique 初始化<$ c $有什么好处? c> std :: unique_ptr ?

What are the advantages of using std::make_unique over the new operator for initializing a std::unique_ptr?

换句话说,为什么

std::unique_ptr<SomeObject> a = std::make_unique(SomeObject(...))

比做得好

std::unique_ptr<SomeObject> a = new SomeObject(...)

我尝试过在线查找很多内容,但我确实知道避免在现代C ++中使用运算符 new 是一个很好的经验法则,但是我不确定在这种情况下有什么优势。是否可以防止可能发生的任何类型的内存泄漏?做 std :: make_unique 比使用 new 更快吗?

I tried looking up a lot online and I do know that it is a good rule of thumb to avoid the operator new in modern C++, but I am not sure what the advantages are in this exact scenario. Does it prevent any kind of memory leaks that might happen? Is it faster to do a std::make_unique than to use new?

推荐答案

优点




  • make_unique 教用户永远不要说 / 删除
    new [] / delete [] 而没有免责声明。

    Advantages

    • make_unique teaches users "never say new/delete and new[]/delete[]" without disclaimers.

      make_unique make_shared 共享两个优点(不包括第三个优势,即提高了效率)。首先, unique_ptr< LongTypeName> up(新LongTypeName(args))必须两次提及 LongTypeName ,而 auto up = make_unique< LongTypeName>(args) 提及一次。

      make_unique shares two advantages with make_shared (excluding the third advantage, increased efficiency). First, unique_ptr<LongTypeName> up(new LongTypeName(args)) must mention LongTypeName twice, while auto up = make_unique<LongTypeName>(args) mentions it once.

      make_unique 可以防止由<$之类的表达式触发的未指定评估顺序的
      泄漏c $ c> foo(unique_ptr< X>(新X),
      unique_ptr< Y>(新Y))。 (遵循不要说的建议比
      不要说 new 更简单,除非您立即将其命名为 unique_ptr 。)

      make_unique prevents the unspecified-evaluation-order leak triggered by expressions like foo(unique_ptr<X>(new X), unique_ptr<Y>(new Y)). (Following the advice "never say new" is simpler than "never say new, unless you immediately give it to a named unique_ptr".)

      make_unique 为实现异常安全而精心实现,建议您直接调用 unique_ptr 构造函数。

      make_unique is carefully implemented for exception safety and is recommended over directly calling unique_ptr constructors.


      • Don如果您需要自定义删除器或从其他地方采用原始指针,请不要使用 make_unique

      • Don't use make_unique if you need a custom deleter or are adopting a raw pointer from elsewhere.

      1. std :: make_unique 的提案。

      2. 草药萨特的GotW#89解决方案:智能指针

      1. Proposal of std::make_unique.
      2. Herb Sutter's GotW #89 Solution: Smart Pointers

      这篇关于与新运算符相比,使用std :: make_unique的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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