[英]Differences between std::make_unique and std::unique_ptr with new internally
This question is a follow up to this question . 这个问题是一个跟进这个问题 。
The accepted answer states: 接受的答案指出:
make_unique
is safe for creating temporaries whereas with explicit use ofnew
you have to remember the rule about not using unnamed temporariesmake_unique
对于创建临时make_unique
是安全的,而显式使用new
则必须记住有关不使用未命名临时文件的规则
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 } );
Into this: 变成这个:
f( make_unique<T1>(), make_unique<T2>() );
Just to avoid the scenario where the compiler orders the actions like the following, because it may do so until C++14 (included): 只是为了避免编译器命令如下操作的情况,因为它可能会在C ++ 14(包括)之前执行:
new T1
new T2
unique_ptr
unique_ptr
unique_ptr
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. 如果第二步(
new T2
)引发异常,则第一个分配的对象尚未固定到unique_ptr
并泄漏。
The make_unique
function is actually simple to write, and has been overlooked for C++11. make_unique
函数实际上很容易编写,而C ++ 11却忽略了它。 It has been easily introduced in C++14. 它已在C ++ 14中轻松引入。 Inbetween, everybody would write their own
make_unique
template, or google the one written by Stephen T. Lavavej. 在这
make_unique
之间,每个人都将编写自己的make_unique
模板,或在Google上搜索由Stephen T. Lavavej编写的模板。
As StoryTeller commented, since C++17, this interleaving is no more allowed. 正如StoryTeller所评论的那样,从C ++ 17开始,不再允许这种交织。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.