C++自动指针实现
来源:互联网 发布:优化后讨鬼传2 psv画质 编辑:程序博客网 时间:2024/06/10 22:25
auto_ptr的实现
以下代码摘录自More Effective C++
auto_ptr.h
#ifndef AUTO_PTR_H#define AUTO_PTR_Htemplate<typename T>class auto_ptr{ public : //使用explicit关键字避免隐式转换 explicit auto_ptr(T* p=0); ~auto_ptr(); //使用另一个类型兼容的auto_ptr来初始化一个新的auto_ptr template<typename U> auto_ptr(auto_ptr<U>& rhs); template<typename U> auto_ptr<T>& operator=(auto_ptr<U>& rhs); T& operator*() const; T* operator->() const; //返回原始对象的指针 T* get() const; //放弃指针的所以权 T* release(); //删除原有指针并获得指针的p的所有权 void reset(T* p=0); private: T* pointee;};template<typename T>auto_ptr<T>::auto_ptr(T* p) :pointee(p){}template<typename T> template<typename U>auto_ptr<T>::auto_ptr(auto_ptr<U>& rhs) :pointee(rhs.release()){}template<typename T>auto_ptr<T>::~auto_ptr(){ delete pointee;}template<typename T> template<typename U>auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<U>& rhs){ if(this!=&rhs) reset(rhs.release()); return *this;}template<typename T>T& auto_ptr<T>::operator*() const{ return *pointee;}template<typename T>T* auto_ptr<T>::operator->() const{ return pointee;}template<typename T>T* auto_ptr<T>::get() const{ return pointee;}template<typename T>T* auto_ptr<T>::release(){ T* oldpointee=pointee; pointee=0; return oldpointee;}template<typename T>void auto_ptr<T>::reset(T* p){ if(pointee!=p) { delete pointee; pointee=p; }}#endif
用来测试的Item类
//Item.h#ifndef ITEM_H#define ITEM_Hclass Item{public: Item(void); ~Item(void); void PrintContent() const;};#endif//Item.cppusing std::cout;using std::endl;Item::Item(void){}Item::~Item(void){ cout<<"Destorying....."<<endl;}void Item::PrintContent() const{ cout<<"Here is the content"<<endl;}
main.cpp
#include <iostream>#include "auto_ptr.h"#include "Item.h"using std::cout;int main(){ auto_ptr<Item> itemPtr(new Item); itemPtr->PrintContent(); auto_ptr<Item> itemPtr2(itemPtr); itemPtr2->PrintContent(); return 0;}
运行程序,可以看到建在堆上的Item对象自动释放了,因为auto_ptr对象析构时将指针pointee delete了,同时结果如下:
Here is the content
Here is the content
Destorying.....
程序只会输出一句Destorying.....,因为在构造itemPtr2时,itemPtr的成员pointee指向的Item已经转交给了itemPtr2中的指针,
所以最后只会看到一句Destorying.....,也就是只有一个Item对象析构了...
- C++自动指针实现
- c 指针实现面向对象
- 【C++】智能指针的实现
- [c++]智能指针的实现
- C 语言实现智能指针
- 自动指针
- 自动指针
- c函数指针实现任意位置跳转
- C语言-用指针实现冒泡排序
- C语言冒泡法用指针实现
- C语言qsort算法的指针实现
- 读书笔记--C 指针实现各项字符串操作
- C语言矩阵乘法(指针实现)
- 《c程序设计语言》读书笔记-5.3-指针实现strcat
- 《c程序设计语言》读书笔记-5.4-指针实现strend
- 【C++】智能指针auto_ptr的简单实现
- C语言指针实现字符串的反转
- C语言函数指针实现接口思想
- 关于学习的一些思考
- 通过cmd创建空白txt文件
- iOS 开源项目list
- DLL编程笔记
- linux diff详解
- C++自动指针实现
- excel IF嵌套
- oseicq介绍
- FTP出现500 OOPS: cannot change directory
- 字符串常量引起的思考
- android中ListView的HeaderView的Padding详解
- POJ 3301 三分
- 戴牛一万行的几何模板
- CentOS中vsftp安装与配置