智能指针

C++语言中没有垃圾回收机制(定期检测,如果没人使用,就回收内存)

内存泄漏:指针指向堆空间,指针变量存在于栈,指针销毁了对应的堆空间没有被销毁。

智能指针原理:

       指针变量声明周期结束时主动的释放堆空间。

智能指针要求:

       1.一个堆空间只由一个指针指向(避免多次释放)。

       2.不可进行指针运算(避免指针越界)。

智能指针实现:

       重载指针操作符(-> 和 *)

重载指针操作符规定:

       1. 只能通过类的成员函数重载。

       2. 重载函数不可使用参数。

       3. 重载函数只能定义一个参数。

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int i;
public:
    Test(int i)
    {
        cout << "Test(int i)" << endl; // new一个pointer时被调用
        this->i = i;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
        cout << "~Test()" << endl;  // pointer对象的析构函数被他调用时调用
    }
};

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;  //删除mp对应空间的内存。(当存在于栈的指针变量被销毁时,对应的指向的堆空间的内存也被销毁
    }
};

int main()
{
    Pointer p1 = new Test(0);
    
    cout << p1->value() << endl;  // 0 
    
    Pointer p2 = p1;  // 将P1指向的堆空间转给P2指针
    
    cout << p1.isNull() << endl;  // NULL
    
    cout << p2->value() << endl;  // 0
    
    return 0;    // 销毁指针变量,销毁变量指向空间
}

智能指针限制:智能指针只能指向堆空间。

原文地址:https://www.cnblogs.com/zsy12138/p/10838741.html