与新运算符相比,使用std :: make_unique的优点 [英] Advantages of using std::make_unique over new operator
问题描述
相对于 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 saynew
/delete
andnew[]
/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 withmake_shared
(excluding the third advantage, increased efficiency). First,unique_ptr<LongTypeName> up(new LongTypeName(args))
must mentionLongTypeName
twice, whileauto 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 likefoo(unique_ptr<X>(new X)
,unique_ptr<Y>(new Y))
. (Following the advice "never saynew
" is simpler than "never saynew
, unless you immediately give it to a namedunique_ptr
".)make_unique
为实现异常安全而精心实现,建议您直接调用unique_ptr
构造函数。make_unique
is carefully implemented for exception safety and is recommended over directly callingunique_ptr
constructors.- Don如果您需要自定义删除器或从其他地方采用原始指针,请不要使用
make_unique
。
- Don't use
make_unique
if you need a custom deleter or are adopting a raw pointer from elsewhere.
- Proposal of
std::make_unique
. - Herb Sutter's GotW #89 Solution: Smart Pointers
这篇关于与新运算符相比,使用std :: make_unique的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Don如果您需要自定义删除器或从其他地方采用原始指针,请不要使用