37-智能指针分析

来源:互联网 发布:青年网络公开课主持人 编辑:程序博客网 时间:2024/06/04 17:42

1、

这里写图片描述

#include <iostream>#include <string>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;}01234但是没有释放指针对应的内存,造成内存泄露

2、需求

这里写图片描述
智能指针是一个类实现指针的功能

3、

这里写图片描述

#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;//将原来的指针赋值为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;}Test(int i)010~Test()

4、

这里写图片描述

5、小结

这里写图片描述