请教:智能指针(auto_ptr)初始化的区别。

qihui_zhu 2007-12-22 12:54:38
在用一个智能指针初始化智能指针时的几种方法有什么不同。
例如:
auto_ptr<string> pstr_auto1(new string("hello word")); //已有智能指针
//下面打算用pstr_auto1初始化pstr_auto2
// auto_ptr<string> pstr_auto2(pstr_auto1); //方法一

// auto_ptr<string> pstr_auto2(pstr_auto1.release()); //方法二
请教方法一和方法二是否完全一样? 如果不一样,请教有什么不同。
我知道方法二执行之后,pstr_auto1就脱离了对内存的控制权,也就相当于pstr_auto1已经失效了。那方法一呢?他们是完全等效么?

// auto_ptr<string> pstr_auto2(pstr_auto1.get()); //方法三 这个应对该是错误的吧
方法三应该是错误的吧,生命期结束后内存会被释放2次。
...全文
279 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qihui_zhu 2007-12-27
  • 打赏
  • 举报
回复
to 2楼
============================

方法3在C++ primer上好像提过是错误的写法
foochow 2007-12-23
  • 打赏
  • 举报
回复
看看auto_ptr的源码不就很清楚了~~
qihui_zhu 2007-12-23
  • 打赏
  • 举报
回复
auto_ptr 别用,用 boost::shared_ptr

============================================
记得好像在书里看到过boost::shared_ptr,还不太了解这个的用法,看来要学习一下。
Oversense 2007-12-23
  • 打赏
  • 举报
回复
auto_ptr 别用,用 boost::shared_ptr
ryfdizuo 2007-12-22
  • 打赏
  • 举报
回复

STL中的auto_ptr指针是为了解决内存泄漏问题而设计的。它严格限制了指针拥有对指向对象的所有权。
auto_ptr指针和普通指针的差别在于对指向对象所有权的处理不同。
auto_ptr指针是“传递”所有权,而普通指针是“共享”所有权。
ryfdizuo 2007-12-22
  • 打赏
  • 举报
回复

测试一下就知道了啊:
#include <memory>
#include <string>
#include <cassert>
#include <iostream>

using namespace std;

int main()
{
auto_ptr<string> pstr_auto1(new string("hello word")); //已有智能指针
//下面打算用pstr_auto1初始化pstr_auto2
//auto_ptr <string> pstr_auto2(pstr_auto1); //方法一
//auto_ptr <string> pstr_auto2(pstr_auto1.release()); //方法二
auto_ptr <string> pstr_auto2(pstr_auto1.get()); //方法三 cout<<*pstr_auto2<<endl;
cout<<*pstr_auto1<<endl;

return 0;
}
auto_ptr是传递使用权的
方法3没有问题;
方法1,2都会抛出异常的,
yshuise 2007-12-22
  • 打赏
  • 举报
回复
方法一可以用:
pstr_auto2 = pstr_auto1;
pstr_auto1没有指向这个对象。pstr_auto2指向了。

64,685

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧