智能指针

我们的项目中就难避免的就是内存泄漏,内存泄漏就是动态申请堆空间,指针无法控制所指堆空间的生命周期,用完后不归还,有的编程语言有垃圾回收的机制,但是我们的C++语言没有垃圾回收机制,为了避免内存泄漏,我就需要一个特殊的指针,指针生命周期结束时主动释放堆空间,而且这一片堆空间最多只能由一个指针标识,还要避免指针运算和指针比较,,所以我们要提出一个解决方案满足上述要求
方案:
重载指针特征操作符(-> 和 *)
只能通过类的成员函数重载
重载函数不能使用参数
只能定义一个重载函数

先来看一个例子:

sice@sice:~$ cat test.cpp
#include <iostream>
#include <string>
using namespace std;
class Test
{
   private:
   int i;
   public:
   Test(int i)
   {
     cout<<"Test(int i)"<<endl;
     this->i = i;
   }
   ~Test()
   {
     cout<<"~Test()"<<endl;
   }
   int value()
   {
     return i;
   }
};
class pointer
{
   private:
   Test *mp;
   public:
   pointer(Test* p = NULL)
   {
     mp = p;
   }
   Test* operator ->()
   {
     return mp;
   }
   Test& operator *()
   {
     return *mp;
   }
   ~pointer()
   {
     delete mp;
   }

};
int main()
{ 
  for(int i=0;i<7;i++)
  {
    pointer p = new Test(i);
    cout<<p->value()<<endl;
  }
  return 0;
}

结果;

Test(int i)
0
~Test()
Test(int i)
1
~Test()
Test(int i)
2
~Test()
Test(int i)
3
~Test()
Test(int i)
4
~Test()
Test(int i)
5
~Test()
Test(int i)
6
~Test()

可以看出我们定义了指针类,还重载操作符函数,实现指针的自动释放,这就是智能指针,是不是很强大!?,还可以改进,为了一片堆空间最多只能由一个指针标识,我们加入拷贝构造函数和操作符重载函数
例子:

#include <iostream>
#include <string>
using namespace std;
class Test
{
   private:
   int i;
   public:
   Test(int i)
   {
     cout<<"Test(int i)"<<endl;
     this->i = i;
   }
   ~Test()
   {
     cout<<"~Test()"<<endl;
   }
   int value()
   {
     return i;
   }
};
class pointer
{
   private:
   Test *mp;
   public:
   pointer(const pointer& obj)
   {
      mp = obj.mp;
      const_cast<pointer&>(obj).mp = NULL;
   }
   pointer& operator =(const pointer&obj)
   {
      if(this != &obj)
      {
        delete mp;
        mp = obj.mp;
        const_cast<pointer&>(obj).mp = NULL;
      }
      return *this;
   }
   pointer(Test* p = NULL)
   {
     mp = p;
   }
   Test* operator ->()
   {
     return mp;
   }
   Test& operator *()
   {
     return *mp;
   }
    bool isNull()
    {
        return (mp == NULL);
    }
   ~pointer()
   {
     delete mp;
   }

};
int main()
{ 
  pointer p = new Test(0);
  cout << p->value() << endl;
  pointer p2 ;//如果改为pointer p2 = p则调用拷贝构造函数
  p2 = p;//
  cout << p.isNull() << endl;
  cout << p2->value() << endl;
  return 0;
}

结果:

sice@sice:~$ ./a.out 
Test(int i)
0
1
0
~Test()

这样我们就能使一片堆空间只能有一个指针指向,特别注意的是智能只能用来指向堆空间中的对象或者变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值