C++ std::unique_ptr 用法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5622764/
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
std::unique_ptr usage
提问by Guillaume07
std::unique_ptr<int> p1(new int);
std::unique_ptr<int> p2(new int);
p2=p1;
It seems here that p1 is no longer "unique" since p2 refer to it also
这里似乎 p1 不再是“唯一的”,因为 p2 也指代它
It is legal c++ ? Does unique_ptr have copy_semantics ? If no, and if it has only move semantics, is p1 set to NULL after assign it to p2 ?
它是合法的 c++ 吗?unique_ptr 有 copy_semantics 吗?如果没有,并且只有移动语义,那么在将 p1 分配给 p2 后是否将其设置为 NULL?
EDIT:
编辑:
ok so the correct version is
好的,所以正确的版本是
p2=std::move(p1)
According to that, after this assign, p1 is not valid ? And the difference with auto_ptr is here? it is more safe to explictly specfiy transfer of ownership than implicitly as it is the case with auto_ptr I guess
据此,在此分配之后,p1 无效?和 auto_ptr 的区别就在这里?显式指定所有权转移比隐式指定更安全,因为我猜 auto_ptr 就是这种情况
回答by Tony The Lion
回答by Howard Hinnant
Here is an article I wrote which answers your questions. I originally wrote this article to present an emulation of unique_ptr. However you can ignore the first few paragraphs dealing with the emulation and just start reading at "Basic Examples".
这是我写的一篇文章,可以回答您的问题。我最初写这篇文章是为了展示 unique_ptr 的模拟。但是,您可以忽略处理仿真的前几段,直接从“基本示例”开始阅读。
http://howardhinnant.github.io/unique_ptr03.html
http://howardhinnant.github.io/unique_ptr03.html
Edit:
编辑:
I had trouble distilling the above linked article down to something small enough to make a practical answer in this format. However here is my best shot:
我无法将上面链接的文章提炼成足够小的内容,无法以这种格式做出实用的答案。然而,这是我最好的镜头:
The reason: Safety in generic code. One can not really make copies of either
auto_ptrorunique_ptr. Consider:template <class T> void foo(T t) { T copy_of_t = t; // line 4 assert(copy_of_t == t); }It is not unusual at all for generic code to look like
fooabove. Theassertis probably not actually there, but the assumption that theassertwould hold often is there ... implicitly. Indeed, a popular implementation ofstd::sorthad exactly this logic in 1996, which is exactly what prompted the secondauto_ptrredesign (which helped, but didn't completely fix the problem).
原因:通用代码的安全性。一个人不能真正制作
auto_ptr或 的副本unique_ptr。考虑:template <class T> void foo(T t) { T copy_of_t = t; // line 4 assert(copy_of_t == t); }通用代码看起来像
foo上面那样并不罕见。Theassert可能实际上并不存在,但assert通常会成立的假设 存在...... 隐含地。事实上,std::sort1996 年的一个流行实现正是这种逻辑,这正是促使第二次auto_ptr重新设计的原因(这有帮助,但并没有完全解决问题)。

