【发布时间】: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<bar> mySecondBar = myFirstBar; C++ 将所有权从 myFirstBar 转移到 mySecondBar 并且没有编译错误。
但是当我使用 unique_ptr 而不是 auto_ptr 时,我得到一个编译器错误。为什么 C++ 不允许这样做?这两个智能指针之间的主要区别是什么?什么时候需要用什么?
【问题讨论】:
标签: c++ c++11 smart-pointers