首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >unique_ptr VS auto_ptr

unique_ptr VS auto_ptr
EN

Stack Overflow用户
提问于 2012-11-21 04:29:53
回答 1查看 17.8K关注 0票数 19

可能重复:

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++不允许这样做?这两个智能指针之间的主要区别是什么?当我需要使用什么的时候?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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));
票数 46
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13481579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档