std :: make_unique和std :: unique_ptr之间的区别 [英] Differences between std::make_unique and std::unique_ptr
问题描述
std :: make_unique
有什么效率好处,例如 std :: makes_shared
?
与手动构建 std :: unique_ptr
相比:
code> 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> // exception safe
foo(unique_ptr< T>(new T()),unique_ptr U() // unsafe *
-
添加
make_unique
finally意味着我们可以告诉人们从不使用new
而不是以前的规则从不使用new
,除非您创建unique_ptr
。
还有第三个原因:
-
make_unique
不需要冗余类型使用。unique_ptr< T>(new T())
- >make_unique< T>()
没有任何原因涉及使用 make_shared
的方式提高运行时效率(由于避免了第二次分配,以牺牲可能更高的峰值内存使用为代价)。
*预计C ++ 17将包含规则更改,这意味着这不再不安全。请参阅C ++委员会文件 P0400R0 和 P0145R3 。 p>
Does std::make_unique
have any efficiency benefits like std::makes_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 ofnew
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' usenew
rather than the previous rule to "'never' usenew
except when you make aunique_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之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!