unique_ptr VS auto_ptr

Mar*_*oun 18 c++ smart-pointers c++11

可能重复:
std :: auto_ptr到std :: unique_ptr有
哪些C++智能指针实现可用?

让我说我有这个struct:

struct bar 
{ 

};
Run Code Online (Sandbox Code Playgroud)

当我像这样使用auto_ptr:

void foo() 
{ 
   auto_ptr<bar> myFirstBar = new bar; 
   if( ) 
   { 
     auto_ptr<bar> mySecondBar = myFirstBar; 
   } 
}
Run Code Online (Sandbox Code Playgroud)

然后在auto_ptr<bar> mySecondBar = myFirstBar;C++中将所有权从myFirstBar传输到mySecondBar,并且没有编译错误.

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

Die*_*ühl 46

std::auto_ptr<T>可能会默默地窃取资源.这可能会让人感到困惑,并且试图将其定义std::auto_ptr<T>为不允许您这样做.随着std::unique_ptr<T>持股比例不被悄悄从任何转移你仍然持有.它仅将所有权从您没有句柄的对象(临时)或即将离开的对象(对象即将超出函数中的作用域)转移.如果你真的想转让所有权,你可以使用std::move():

std::unique_ptr<bar> b0(new bar());
std::unique_ptr<bar> b1(std::move(b0));
Run Code Online (Sandbox Code Playgroud)

  • 次要评论,第一行应该是`new bar`,而不是`new std :: unique_ptr <bar>` (4认同)