c++ - unique_ptr VS auto_ptr

标签 c++ c++11 smart-pointers

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/

相关文章:

c++ - 条件 constexpr 函数

c++ - 智能指针不适用于 Android NDK r8

C++ `using` 模板类中类型别名的命令

python - 将图像数据从 python 传递到 c++ 中的 cv::mat

c++ - 用于用户输入的 Linux C++ gdb 命令

c++ - 为什么我们必须为带有默认参数的模板类指定<>?

c++ - 如何正确地将 _bstr_t 重置为 `NULL`

c++ - 如何在 C 中包装返回智能指针的 C++ 函数?

C++ 使用 __COUNTER__ 自动生成不同的命名函数

C++ lua表映射到lua文件