2012-11-20 74 views
16

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

可以说我有这个struct

struct bar 
{ 

}; 

当我使用auto_ptr的这样的:

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

然后在auto_ptr<bar> mySecondBar = myFirstBar; C++传送从myFirstBar到mySecondBar所有权并且没有编译错误。

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

+1

见http://stackoverflow.com/questions/5026197/what-c​​-smart-pointer-implementations-are-available – hmjd

回答

42

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)); 
+4

小评论,第一行应该是'new bar',而不是'new std :: unique_ptr ' –

+0

@DaveS:当然可以。我已经解决了答案。谢谢! –