C++:智能指针_auto_ptr_vc版本
来源:互联网 发布:杀破狼 js 无损下载 编辑:程序博客网 时间:2024/06/18 02:15
智能指针_auto_ptr_vc版本:
拥有权管理和转移:
我们让指针给指针初始化的时候将拥有权进行转移,即指针1被指针2初始化后,指针1拥有了管理该对象的权利,会进行析构该对象,而指针2不会对该对象进行析构
<span style="font-size:18px;">#include <iostream>#include <memory>using namespace std;template <class _Ty>class auto_ptr{public:auto_ptr(_Ty *_P=0):_Owns(_P!=0),_Ptr(_P){}//智能指针初始化的时候,需要将拥有权进行转移//将拥有权赋值给新的指针,自身的拥有权进行释放auto_ptr(const auto_ptr<_Ty> &_Y):_Owns(_Y._Owns),_Ptr(_Y.release()) {}auto_ptr<_Ty>& operator=(const auto_ptr<_Ty> &_Y){//pa2 = pa1if(this != &_Y) {if(_Ptr != _Y._Ptr) //pa2和pa1指向不相同{if(_Owns) //pa2有指向,则析构pa2的指向 delete _Ptr; _Owns = _Y.Owns; //将pa1的拥有权进行转移}else if(_Y.Owns) //p2和p1指向相同,判断p1是否有拥有权,有则将拥有权转移_Owns = true;_Ptr = _Y.release(); //将pa1的拥有权进行释放,并将指针赋值给pa2}return *this;}~auto_ptr() {if(_Owns) //当拥有权为真时,析构指针delete _Ptr;}public:_Ty& operator*()const //*p{return *_Ptr;}_Ty* operator->()const //p->{return _Ptr;}_Ty* release()const //将拥有权释放,并返回指针{//将拥有权释放((auto_ptr<_Ty>*)this)->_Owns = false;return _Ptr;}private:bool _Owns;_Ty *_Ptr;};class Test{public:void fun()const{cout<<"This is Test fun()"<<endl;}};int main(){int *p = new int(10);auto_ptr<int> pa(p);cout<<*pa<<endl;auto_ptr<int> pa1 = pa;cout<<*pa1<<endl;auto_ptr<int> pa2;pa2 = pa;cout<<*pa2<<endl;return 0;}</span>
pa2 = pa1 的时候:
1.pa2 无指向 : 将pa1的指针给pa2赋值,再将pa1将拥有权进行转移;
2.pa2 有指向不同于pa1的对象 : 将pa2的指向进行析构,再将pa1的指针给pa2赋值,将pa1的拥有权转移;
3.pa2 有指向和pa1相同的对象 : 判断pa1是否有拥有权,有则将pa1的拥有权转移给pa2。
但vc版的auot_ptr也有一些问题,就是将拥有权转移后,除了不能够对其多次析构外,还可以对其进行操作,这就不好了,你都已经分手了,还不放手。
在VS版本上对拥有权有更好的管理。
0 0
- C++:智能指针_auto_ptr_vc版本
- C++:智能指针_auto_ptr_vs版本
- c++:智能指针
- C++:智能指针
- 【C++】智能指针
- 【C++】智能指针
- C++PJ智能指针
- 【c++】智能指针
- 【C++】智能指针auto_ptr
- C++,智能指针
- C++,boost智能指针
- 智能指针模拟C
- [C++]智能指针
- 【C++】 浅析智能指针
- C++_智能指针
- C++:初识智能指针
- C++::智能指针
- 【C++】智能指针
- 莫队算法讲解(含树上莫队)
- Ford-Fulkerson 标号法求网络最大流
- WAMP 何如更新PHPMyAdmin版本
- sdut oj2127 树-堆结构练习——合并果子之哈夫曼树(优先队列)
- 网络爬虫之java基础篇QueryRunner(Ⅲ)
- C++:智能指针_auto_ptr_vc版本
- sklearn K-means MiniBatch-K-Means
- 【BZOJ2002】弹飞绵羊
- 数字锁相放大
- Linux 虚拟内存和物理内存的理解
- 素数判定
- NSTimer定时器
- 【Java】MD5编码加密-code片段
- 用C++实现文件压缩