【问题标题】:unique_ptr VS auto_ptr [duplicate]unique_ptr VS auto_ptr [重复]
【发布时间】:2012-11-20 20:29:53
【问题描述】:

可能重复:
std::auto_ptr to std::unique_ptr
What C++ Smart Pointer Implementations are available?

假设我有这个struct

struct bar 
{ 

};

当我像这样使用 auto_ptr 时:

void foo() 
{ 
   auto_ptr<bar> myFirstBar = new bar; 
   if( ) 
   { 
     auto_ptr<bar> mySecondBar = myFirstBar; 
   } 
}

然后在auto_ptr&lt;bar&gt; mySecondBar = myFirstBar; C++ 将所有权从 myFirstBar 转移到 mySecondBar 并且没有编译错误。

但是当我使用 unique_ptr 而不是 auto_ptr 时,我得到一个编译器错误。为什么 C++ 不允许这样做?这两个智能指针之间的主要区别是什么?什么时候需要用什么?

【问题讨论】:

标签: c++ c++11 smart-pointers


【解决方案1】:

std::auto_ptr&lt;T&gt; 可能会默默地窃取资源。这可能会令人困惑,并试图定义 std::auto_ptr&lt;T&gt; 以不允许您这样做。使用std::unique_ptr&lt;T&gt;,所有权不会从您仍持有的任何东西中悄悄转移。它仅从您没有句柄的对象(临时)或即将消失的对象(即将超出函数范围的对象)转移所有权。如果你真的想转让所有权,你可以使用std::move()

std::unique_ptr<bar> b0(new bar());
std::unique_ptr<bar> b1(std::move(b0));

【讨论】:

  • 次要注释,第一行应该是new bar,而不是new std::unique_ptr&lt;bar&gt;
  • @DaveS:是的,当然。我已经确定了答案。谢谢!
  • 我认为“静默传输”是 auto_ptr 的问题。
猜你喜欢
  • 2013-08-18
  • 2011-03-27
  • 1970-01-01
  • 2013-12-09
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
相关资源
最近更新 更多