C++ std::unique_ptr 的推荐用法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15476907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Recommended usage of std::unique_ptr
提问by Mushy
What are recommended uses of a std::unique_ptr
as to specifically where, when, and how is it is best used?
a 的推荐用途是什么std::unique_ptr
,特别是在何处、何时以及如何最好地使用它?
I discovered:
我发现:
I already know:
我已经知道:
std::unique_ptr
was developed in C++11 as a replacement forstd::auto_ptr
- That a
std::unique_ptr
has no reference counting and "owns" object it points to - There is no copy/assign with a
std::unique_ptr
- When I need a unique pointer,
std::unique_ptr
is the go to structure
std::unique_ptr
是在 C++11 中开发的,作为替代std::auto_ptr
- a
std::unique_ptr
没有引用计数并且“拥有”它指向的对象 - 没有复制/分配
std::unique_ptr
- 当我需要一个唯一的指针时,
std::unique_ptr
是转到结构
What I would like to know:
我想知道的是:
- Is using a
std::unique_ptr
ever preferable (other than uniqueness) to something
else? What do I gain in this situation? - If so, under what circumstances and when?
- Given the need for move semantics, would this make a
std::unique_ptr
less favorable
overall? - If a
std::shared_ptr
would suffice for dynamic memory management in nearly every situation, why does having at my disposal astd::unique_ptr
matter (again, other
than uniqueness)?
- 使用
std::unique_ptr
比其他东西更可取的(除了唯一性)
吗?在这种情况下我能得到什么? - 如果是,在什么情况下,什么时候?
- 考虑到移动语义的需要,这是否会使
总体上
std::unique_ptr
不太有利
? - 如果 a
std::shared_ptr
几乎在所有情况下都足以进行动态内存管理,那么为什么我可以随意使用它std::unique_ptr
(同样,
除了唯一性之外)?
回答by Kate Gregory
In theory, you should use unique_ptr
for all pointers unless you know you want to share it, in which case you should use shared_ptr
. The reason is that unique_ptr
has less overhead since it doesn't count references.
理论上,您应该使用unique_ptr
for 所有指针,除非您知道要共享它,在这种情况下,您应该使用shared_ptr
. 原因是它的unique_ptr
开销较少,因为它不计算引用。
However, a unique_ptr
is movable but not copyable, so using one as a member variable can require you to write more code (eg a move constructor), passing one by value means you'll need to use std::move
and so on. As a result some people use shared_ptr
out of laziness, because it's just easier, and the perf difference may not be significant for their app.
但是, aunique_ptr
是可移动的但不可复制,因此将其用作成员变量可能需要您编写更多代码(例如移动构造函数),按值传递一个意味着您需要使用std::move
等等。因此,有些人shared_ptr
出于懒惰而使用它,因为它更容易,而且性能差异对于他们的应用程序来说可能并不重要。
Finally a raw pointer is fine for observation - pointer uses that can never affect lifetime. Careful choice of the right pointer type can give those who read your code a good understanding of what you are doing. For more, see Herb Sutter's essay, Elements of C++ Style, specifically the "no delete" section.
最后,原始指针适合观察 - 指针使用永远不会影响生命周期。仔细选择正确的指针类型可以让阅读你代码的人很好地理解你在做什么。有关更多信息,请参阅 Herb Sutter 的文章Elements of C++ Style,特别是“不可删除”部分。