智能指针分析

2021/12/1 6:08:41

本文主要是介绍智能指针分析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

智能指针为了解决内存泄漏的问题而诞生

内存泄漏:
(1)动态申请堆空间,用完后不归还
(2)C++语言中没有垃圾回收的机制
(3)指针无法控制所指堆空间的生命周期

编程实验:内存实验

#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;
}

深度思考:
我们需要什么?
(1)需要一个特殊的指针
(2)指针生命周期结束时主动释放堆空间
(3)一片堆空间最多只能由一个指针表示
(4)杜绝指针运算和指针比较
解决方案
(1)重载指针特征操作符(->和*
(2)只能通过类的成员函数重载
(3)重载函数不能使用参数
(4)只能定义一个重载函数

编程实验:智能指针

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
        cout << "Test" << endl;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
        cout << "~Test()" << endl;
    }
};

class Pointer
{
    Test* mp;
public:
    Pointer(Test* p = NULL)
    {
        mp = p;
        cout << "Pointer" << endl;
    }
    Test* operator -> ()
    {
        return mp;
    }
    Test& operator * ()
    {
        return *mp;
    }
    ~Pointer()
    {
        delete mp;
        cout << "~Pointer()" << endl;
    }
};
int main()
{
    for(int i = 0; i < 5; i++)
    {
        Pointer p = new Test(i);

        cout << p->value() << endl;
    }

    return 0;
}

在这里插入图片描述

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
        cout << "Test" << endl;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
        cout << "~Test()" << endl;
    }
};

class Pointer
{
    Test* mp;
public:
    Pointer(Test* p = NULL)
    {
        mp = p;
        cout << "Pointer" << endl;
    }
    Pointer(const Pointer& obj)
    {
        mp = obj.mp;
        const_cast<Pointer&>(obj).mp = NULL;
        cout << "Pointer(const Pointer& obj)" << endl;
    }
    Pointer& operator=(const Pointer& obj)
    {
        if(this != &obj)
        {
            delete mp;
            mp = obj.mp;
            const_cast<Pointer&>(obj).mp = NULL;
            cout << "Pointer& operator=" << endl;
        }

        return *this;
    }
    bool isNULL()
    {
        return (mp == NULL);
    }
    Test* operator -> ()
    {
        return mp;
    }
    Test& operator * ()
    {
        return *mp;
    }
    ~Pointer()
    {
        delete mp;
        cout << "~Pointer()" << endl;
    }
};
int main()
{
    Pointer p1 = new Test(0);
    cout << p1->value() << endl;

    Pointer p2 = p1;
    cout << p1.isNULL() << endl;
    cout << p2->value() << endl;

    return 0;
}

在这里插入图片描述

智能指针使用军规:
只能用来指向堆空间中的对象或者变量
小结:
(1)重载智能指针特征符能够使用对象代替指针
(2)智能指针只能用于指向堆空间中的内存



这篇关于智能指针分析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程