关于指针:c+内存泄漏与智能指针

4次阅读

共计 1195 个字符,预计需要花费 3 分钟才能阅读完成。

您好,看到文章的您,如果您是 c ++ 初学者,这部分内容须要学习好数据结构中指针和栈的内容,否则可能会有肯定难度,只做理解即可

什么是内存透露

什么是内存透露,简略来说,就是

1. 动静申请堆空间,用完后不偿还
2。C++ 语言中没有垃圾回收的机制
3. 指针无法控制所指堆空间的生命周期 


例如上面的例子:

#include<iostream>
#include<string.h>
using namespace std;
class test
{
    int i;
public:
    test(int i)
    {this->i = i;}
    int value()
    {return i;}

    ~test()
    {}};
int main()
{for (int i = 0; i < 5; i++)
    {test* p = new test(i);
        cout << p->value() << endl;}
    return 0;
}

智能指针的利用

从输入后果能够看出,指针被用于了大小比拟和运算,这显然不是咱们冀望的。
于是有了智能指针,demo 如下:

#include <iostream>
#include <string>
using namespace std;
class Test
{
  int i;
public:
  Test(int i)
  {cout << "Test(int i)" << endl;
      this->i = i;
  }
  int value()
  {return i;}
  ~Test()
  {cout << "~Test()" << endl;
  }
};
class Pointer
{
  Test* mp;
public:
  Pointer(Test* p = NULL)
  {mp = p;}
  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;
  }
  Test* operator -> ()
  {return mp;}
  Test& operator * ()
  {return *mp;}
  bool isNull()
  {return (mp == NULL);
  }
  ~Pointer()
  {delete mp;}
};
int main()
{Pointer p1 = new Test(0);
  cout << p1->value() << endl;
  Pointer p2 = p1;
  cout << p1.isNull() << endl;
  cout << p2->value() << endl;
  return 0;
}

这里次要解决的以下问题

 重载指针特色操作符 (-> 和 *)
只能通过类的成员函数重载
重载函数不能应用参数
只能定义一个重载函数 

总结

 指针特色操作符(-> 和 * ) 能够被重载
重载指针特色符可能应用对象代替指针
智能指针只能用于指向堆空间中的内存
智能指针的意义在于最大水平的防止内存问题 
正文完
 0