std::make_unique 和 std::unique_ptr 与 new 内部的区别 [英] Differences between std::make_unique and std::unique_ptr with new internally

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

问题描述

这个问题是对这个问题的跟进.

接受的答案指出:

make_unique 可以安全地创建临时文件,而在显式使用 new 时,您必须记住不使用未命名临时文件的规则

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

我大致了解了这意味着什么并且我理解给出的示例,但是这在内部究竟是如何工作的?这些功能究竟是做什么的,有什么不同?

I get the rough idea what is meant by this and I understand the example given, but how exactly does this work internally? What do these functions do exactly and where is the difference?

推荐答案

这些函数究竟做了什么,区别在哪里?

What do these functions do exactly and where is the difference?

实际上没有什么神奇的.他们只是从这个转换用户代码:

Nothing magical actually. They just transform user code from this:

f( std::unique_ptr<T1>{ new T1 }, std::unique_ptr<T2>{ new T2 } );

进入这个:

f( make_unique<T1>(), make_unique<T2>() );

只是为了避免编译器命令如下操作的场景,因为它可能会在 C++14(包括)之前这样做:

Just to avoid the scenario where the compiler orders the actions like the following, because it may do so until C++14 (included):

  • 新 T1
  • 新 T2
  • 先构建unique_ptr
  • 构建第二个unique_ptr

如果第二步 (new T2) 抛出异常,则第一个分配的对象尚未被保护到 unique_ptr 中并泄漏.

If the second step (new T2) throws an exception, the first allocated object has not yet been secured into a unique_ptr and leaks.

make_unique 函数实际上编写起来很简单,但在 C++11 中却被忽略了.它在 C++14 中很容易被引入.在这期间,每个人都会编写自己的 make_unique 模板,或者在 google 上搜索 Stephen T. Lavavej 编写的模板.

The make_unique function is actually simple to write, and has been overlooked for C++11. It has been easily introduced in C++14. Inbetween, everybody would write their own make_unique template, or google the one written by Stephen T. Lavavej.

正如 StoryTeller 评论的那样,从 C++17 开始,不再允许这种交错.

As StoryTeller commented, since C++17, this interleaving is no more allowed.

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

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