STL学习之auto_ptr
来源:互联网 发布:现代车钥匙淘宝图片 编辑:程序博客网 时间:2024/05/27 21:50
C++标准程序库提供的auto_ptr是一种智能型指针,帮助程序员防止”被异常抛出时发生资源泄漏“。
1、auto_ptr的初始化
template <class _Tp> class auto_ptr {private: _Tp* _M_ptr;public: typedef _Tp element_type; explicit auto_ptr(_Tp* __p = 0) __STL_NOTHROW : _M_ptr(__p) {} auto_ptr(auto_ptr& __a) __STL_NOTHROW : _M_ptr(__a.release()) {}#ifdef __STL_MEMBER_TEMPLATES template <class _Tp1> auto_ptr(auto_ptr<_Tp1>& __a) __STL_NOTHROW : _M_ptr(__a.release()) {}#endif /* __STL_MEMBER_TEMPLATES */上面是STL源代码中class auto_ptr定义的一部分,由上面可以看出一般指针的初始化式不适应于auto_ptr。
auto_ptr可能的初始化式如下:
std::auto_ptr<ClassA> ptr1(new ClassA);//OKstd::auto_ptr<ClassA> ptr2(ptr1);//OKstd::auto_ptr<ClassA> ptr3 = new ClassA;//ERROR
2、auto_ptr的所有权问题
C++标准程序库中规定了一个对象只能被一个auto_ptr对象拥有。
std::auto_ptr<ClassA> ptr1(new ClassA);std::auto_ptr<ClassA> ptr2(ptr1);//ptr1不再拥有new出来的ClassA对象,所有权转移给ptr2这点在将auto_ptr作为参数转递给函数时尤为重要,因为这样会导致原来的auto_ptr不再所有之前的对象,后期如果有针对该对象的类的操作,就会发生错误。
void fun(std::auto_ptr<ClassA> p){//do-something}int main(){std::auto_ptr<ClassA> ptr(new ClassA);fun(ptr);//当fun运行时,ptr已经不再拥有new出来的ClassA//do-something on ptr //这时如果再在ptr上操作就会发生错误}
3、使用const 限定符来禁止所有权的转移
将auto_ptr加上const限定符后对象的所有权就不能再转移了。另外需要指出的是这里的关键词只是说明不能更改auto_ptr的拥有权,但是可是更改其所拥有的对象。
void fun(const std::auto_ptr<ClassA> p){//do-something}int main(){const std::auto_ptr<ClassA> ptr(new ClassA);fun(ptr);//当fun运行时,ptr仍然拥有new出来的ClassA//do-something on ptr //这时继续操作ptr就不会出错ClassA m;*ptr = m;//可以改ptr所拥有的对象}
- STL学习之auto_ptr
- C++ STL 之 auto_ptr
- STL之auto_ptr智能指针
- STL-auto_ptr
- STL auto_ptr
- STL学习笔记——auto_ptr
- VC++界面编程之--使用STL auto_ptr管理GDI+对象
- C++学习之auto_ptr智能指针
- STL中的auto_ptr指针
- stl智能指针auto_ptr
- 剖析STL auto_ptr源码
- STL--智能指针(auto_ptr)
- stl智能指针auto_ptr
- auto_ptr STL智能指针
- STL---auto_ptr实现
- 【STL】智能指针auto_ptr
- 学习auto_ptr
- 学习auto_ptr
- WebKit中CSS处理流程(四)
- Window32 Application和Window32 console Application的区别
- tomcat6 数据库链接配置 .
- 黑马程序员_IO(上)
- 连连看外挂,可以实现无限时间和无限提示
- STL学习之auto_ptr
- 跟我一起写 Makefile(十四)
- UILongPressGestureRecognizer
- UT5 R3命令行连接无线网络
- Hadoop回收站trash
- glog多线程下按照指定条件创建新的日志文件
- SQL中EXISTS的用法
- JSP-----request获取路径总结
- C#:父类的值赋给子类