博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++标准库:智能指针auto_ptr
阅读量:2051 次
发布时间:2019-04-28

本文共 1538 字,大约阅读时间需要 5 分钟。

      auto_ptr类是一个类型形参的模版,它为动态分配的对象提供异常安全,它在头文件memory中定义。

      如果通过常规指针分配内存,而且在执行delete之前发生异常,并且该异常不被局部捕获,就不会自动释放该内存。如果使用一个auto_ptr对象来代替,将会自动释放内存。在最常见的情况下,将auto_ptr对象初始化为由new表达式返回的对象的地址,例如:

     int *p = new int(10);

     auto_ptr<int> ap(p);

auto_ptr只能用于管理从new返回的一个对象,它不能管理动态分配的数组,而且当auto_ptr被复制或赋值的时候,将基础对象的所有权从auto_ptr对象转给副本,原来的auto_ptr对象重置为未绑定状态,所以不能将auto_ptr存储在标准库类型中。

注意:

1.

     int *p = new int(10);

     auto_ptr<int> ap1(p);

     auto_ptr<int< ap2(p);

这样做是不可以的,因为ap1与ap2都认为指针p是归它管的,在析构时都试图删除p, 两次删除同一个对象的行为在C++标准中是未定义的。所以我们必须防止这样使用auto_ptr.。

2.

int* pa = new int[10];

auto_ptr<int> ap(pa);

因为auto_ptr的析构函数中删除指针用的是delete,而不是delete [],所以我们不应该用auto_ptr来管理一个数组指针。

 

 

 

下面是auto_ptr的定义:

namespace std {     template 
struct auto_ptr_ref {}; template
class auto_ptr { public: typedef X element_type; // 20.4.5.1 construct/copy/destroy: explicit auto_ptr(X* p =0) throw(); auto_ptr(auto_ptr&) throw(); template
auto_ptr(auto_ptr
&) throw(); auto_ptr& operator=(auto_ptr&) throw(); template
auto_ptr& operator=(auto_ptr
&) throw(); auto_ptr& operator=(auto_ptr_ref
) throw(); ~auto_ptr() throw(); // 20.4.5.2 members: X& operator*() const throw(); X* operator->() const throw(); X* get() const throw(); X* release() throw(); void reset(X* p =0) throw(); // 20.4.5.3 conversions: auto_ptr(auto_ptr_ref
) throw(); template
operator auto_ptr_ref
() throw(); template
operator auto_ptr
() throw(); }; }

 

 

转载地址:http://bwklf.baihongyu.com/

你可能感兴趣的文章
【Python练习】文件引用用户名密码登录系统
查看>>
学习网站汇总
查看>>
【Python】用Python打开csv和xml文件
查看>>
【Loadrunner】性能测试报告实战
查看>>
【面试】一份自我介绍模板
查看>>
【自动化测试】自动化测试需要了解的的一些事情。
查看>>
【selenium】selenium ide的安装过程
查看>>
【手机自动化测试】monkey测试
查看>>
【英语】软件开发常用英语词汇
查看>>
Fiddler 抓包工具总结
查看>>
【雅思】雅思需要购买和准备的学习资料
查看>>
【雅思】雅思写作作业(1)
查看>>
【雅思】【大作文】【审题作业】关于同不同意的审题作业(重点)
查看>>
【Loadrunner】通过loadrunner录制时候有事件但是白页无法出来登录页怎么办?
查看>>
【Python】Python 读取csv的某行或某列数据
查看>>
【Loadrunner】平台1.9环境APP成功录制并调试成功后的脚本备份
查看>>
【Loadrunner】性能测试:通过服务器日志获取性能需求
查看>>
【Python】sasa版:文件中csv读取在写入csv读取的数据和执行是否成功。
查看>>
【loadrunner】【scorm学习】demo/test域上进行scorm脚本录制及回放成功脚本备份
查看>>
【Loadrunner】使用LoadRunner上传及下载文件
查看>>