可能重复:
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++不允许这样做?这两个智能指针之间的主要区别是什么?当我需要使用什么的时候?
发布于 2012-11-21 04:33:55
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));
https://stackoverflow.com/questions/13481579
复制相似问题