Possible Duplicate:
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<bar> mySecondBar = myFirstBar;
C++ 将所有权从 myFirstBar 转移到 mySecondBar 并且没有编译错误。
但是当我使用 unique_ptr 而不是 auto_ptr 时,我得到一个编译器错误。为什么 C++ 不允许这样做?这两个智能指针之间的主要区别是什么?什么时候需要用什么?
最佳答案
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));
关于c++ - unique_ptr VS auto_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13481579/