现在的位置: 首页 > 综合 > 正文

简单模拟实现c++智能指针-指针移交控制权

2018年03月21日 ⁄ 综合 ⁄ 共 2098字 ⁄ 字号 评论关闭

头文件:autoptr.h

 

#ifndef _AUTOPTR

#define _AUTOPTR  1

 

#include<iostream>

using namespace std;

 

template<class T>

class autoptr

{

public:

       autoptr(T* p=NULL,bool iscontrl=false):p(p),iscontrl(iscontrl)  //构造函数创建对象

       {

              if(p!=NULL)                                                  //如果p指向的不为空,则指针指向动态创建的内存

              {

                     iscontrl=true;                                          //iscontrl表示智能指针控制当前内存

                     cout<<"智能指针创建对象"<<endl;

              }

       }

       T* operator->()

       {

              returnp;

       }

       T& operator*()

       {

              return*p;

       }

       ~autoptr()                                                         //析构函数 如果p指向了动态分配的内存,指针对象析构时要释放该内存空间

       {

              if(p!=NULL)

              {

                     deletep;

                     iscontrl=false;                                            //当指针释放了该内存空间,则指针控制权为false

                     cout<<"智能指针释放对象"<<endl;

              }

       }

       autoptr(autoptr<T>& ptr):p(ptr.p),iscontrl(ptr.iscontrl)          //拷贝构造函数

       {

              ptr.iscontrl=false;

              ptr.p=NULL;

             

       }

   autoptr &       operator=(autoptr<T>& ptr)                            //赋值运算符函数

       {

             

              this->p=ptr.p;

              ptr.p=NULL;

              this->iscontrl=ptr.iscontrl;

              ptr.iscontrl=false;

              return*this;

 

       }

                                                                          //拷贝构造和赋值运算符函数都会使当前的指针失去对内存空间的控制权,并

                                                                          //将控制权移交给其他同类指针

       T*  getp()

       {

              returnp;

       }

      

private:

       T* p;

       booliscontrl;

};

 

#endif

 

 

Main.cpp

 

#include "autoptr.h"

 

 

int main()

{

       autoptr<int>a=new int(10);                         //创建智能指针对象

       cout<<"对象a:"<<*a<<"地址:"<<a.getp()<<endl;

       autoptr<int>b;

       b=a;

       cout<<"移交控制权的对象a:"<<"地址:"<<a.getp()<<endl;//将a指针控制的内存空间控制权移交给b,a对该内存空间失去控制权

       cout<<"对象b:"<<*b<<"地址:"<<b.getp()<<endl;

       autoptr<int>c=b;

       cout<<"移交控制权的对象b:"<<"地址:"<<b.getp()<<endl;

       cout<<"对象c:"<<*c<<"地址:"<<c.getp()<<endl;

       return0;

}

运行结果:

抱歉!评论已关闭.