探索智能指针
来源:互联网 发布:oracle 恢复数据 编辑:程序博客网 时间:2024/05/18 01:03
代码如下,不过这个智能指针有个缺陷,就是只能指向在堆中创建的对象,加以修改后可以改成只能指向在栈中创建的对象,但是无法兼顾两种情况(如果要兼顾两种情况,则智能指针只能指向对象的新建副本,这又失去了指针原有的含义,so...)
#include <iostream>using namespace std;class Object//能被智能指针所指的类{public:void ShowAddress(){cout << "对象的地址为"<<this <<endl ;}~Object(){cout <<"地址为:" <<this <<"的对象释放完毕" <<endl;}void SayHello(){cout <<"Hello world!" <<endl;}};class CPtr//智能代理指针{private:Object* mRealPtr;int mUse;public:friend class SmartPoiter;CPtr(Object* ptr){mRealPtr = ptr;//修改词句,让mRealPtr指向对象的副本,则可以兼顾既可以指向堆,也可以指向栈中的对象mUse = 1;}~CPtr(){cout << "对象引用次数为为0了,将导致释放智能代理指针,此过程也将导致对象释放" << endl;delete mRealPtr;//去掉词句,可以指向在栈中分配的对象}};class SmartPoiter//智能指针类{private:CPtr* mPtr;public:SmartPoiter(Object * p){mPtr = new CPtr(p);}SmartPoiter(SmartPoiter& o){if(this != &o){mPtr = o.mPtr;++(mPtr->mUse);}}SmartPoiter& operator =(SmartPoiter& o){if(this != &o){mPtr = o.mPtr;++(mPtr->mUse);}return *this;}~SmartPoiter(){cout << "析构智能指针对象,释放后引用对象的引用计数为"<< --(mPtr->mUse) << endl;if(mPtr->mUse == 0)delete mPtr;}void ShowAddress(){cout <<"这个智能指针对象指向的对象的地址为"<< mPtr->mRealPtr <<" 这个引用对象的使用计数为" << mPtr->mUse << endl;}//使其支持指针操作Object& operator *()//重载*,以模拟指针操作{return *(mPtr->mRealPtr);}Object* operator->()//重载->,以模拟指针操作{return mPtr->mRealPtr;}};int main(){Object* ob = new Object();ob ->ShowAddress();SmartPoiter A(ob);A.ShowAddress();SmartPoiter B(A);B.ShowAddress();SmartPoiter C = A;C.ShowAddress();A = A;//测试自我赋值问题A.ShowAddress();B.ShowAddress();C.ShowAddress();(*A).ShowAddress();B->ShowAddress();B->SayHello();return 1;}
运行结果如下
- 探索智能指针
- 深度探索智能指针(SmartPointer)
- 深度探索智能指针(Smart Pointer)
- C++深度探索系列:智能指针(Smart Pointer) [一]
- C++深度探索系列:智能指针(Smart Pointer) [二]
- C++深度探索系列:智能指针(Smart Pointer) /1
- C++深度探索系列:智能指针(Smart Pointer) /2
- C++深度探索系列:智能指针(Smart Pointer)[一]
- C++深度探索系列:智能指针(Smart Pointer) [二]
- C++深度探索系列:智能指针(Smart Pointer)
- C++深度探索系列:智能指针(Smart Pointer)
- [zz] C++深度探索系列:智能指针(Smart Pointer) [二]
- C++深度探索系列:智能指针(Smart Pointer) [一]
- C++深度探索系列:智能指针(Smart Pointer) [一]
- C++深度探索系列:智能指针(Smart Pointer) [二]
- 探索WebKit内核(五):智能指针解析
- C++深度探索系列:智能指针(Smart Pointer) [一] (转)
- C++深度探索系列:智能指针(Smart Pointer) [二] (转)
- apache2.2.x+php5.2.x在windows上的安装方法(免拷贝dll和ini)
- servfox解析
- 一步一步写算法(之字符串查找 上篇)
- 继续探讨三层关系
- 删除右键菜单中多余项的常用方法
- 探索智能指针
- Flickr 网站架构分析
- 《Linux那些事儿之我是USB》我是U盘(24)彼岸花的传说(三)
- java propertyChangeListener 观察者模式的实现
- the given port name does not start with COM/com异常解决办法
- 在visual studio 2008下编译C程序
- unix环境高级编程-mkdir和rmdir函数
- Linux C 编程一站式学习 第25章 C标准库 综合练习二题解 文件格式转换
- 【观光旅游】解题报告