【C++】 37_智能指针分析

发布时间:2019-06-24 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【C++】 37_智能指针分析脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

永恒的话题

  • 内存泄漏(臭名昭著的 Bug)

    • 动态申请堆空间,用完后不归还
    • C++ 语言中没有垃圾回收的机制
    • 指针无法控制所指堆空间的生命周期

编程实验: 内存泄漏

#include <iostream>
#include <string>

using namespace std;

class Test
{
private:
    int i;
public:
    Test(int i)
    {
        this->i = i;
    }
    int value()
    {
        return i;
    }
    ~Test()
    {
    }
};

int main()
{
    for(int i=0; i<5; i++)          // 如果是 5000000 次呢?
    {
        Test* p = new Test(i);
        
        cout << p->value() << endl;
    }

    return 0;
}
输出:
0
1
2
3
4

深度的思考

  • 我们需要什么

    • 需要一个特殊的指针
    • 指针生命周期结束时主动释放堆空间
    • 一块堆空间最多只能由一个指针表示(避免内存多次释放)
    • 杜绝指针运算和指针比较(避免越界造成野指针)

智指针分析

  • 解决方案

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

编程实验: 智能指针

#include <iostream>
#include <string>

using namespace std;

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

class Poniter
{
private:
    Test* m_pointer;
public:
    Poniter(Test* p = NULL)
    {
        m_pointer = p;
    }
    Poniter(const Poniter& obj)
    {
        m_pointer = obj.m_pointer;                    // 所有权转接
        const_cast<Poniter&>(obj).m_pointer = NULL;
    }
    Poniter& operator = (const Poniter& obj)
    {    
        if( this != &obj )
        {
            delete m_pointer;                         // 所有权转接
            m_pointer = obj.m_pointer;
            const_cast<Poniter&>(obj).m_pointer = NULL;        
        }
        
        return *this;
    }
    Test* operator -> ()
    {
        return m_pointer;
    }
    Test& operator * ()
    {
        return *m_pointer;
    }
    bool isNull()
    {
        return (m_pointer == NULL);
    }
    ~Poniter()
    {
        delete m_pointer; 
    }
};

int main()
{
    Poniter p1 = new Test(0);
    
    cout << p1->value() << endl;
    
    Poniter p2 = p1;
    
    cout << p1.isNull() << endl;
    cout << p2->value() << endl;

    return 0;
}
输出:
Test(int i)
0
1
0
~Test()
  • 智能指针的使用军规: 只能用来指向堆空间中的对象或者变量

小结

  • 指针特征操作符 ( -> 和 * ) 可以被重载
  • 重载指针特征符能够使用对象代替指针
  • 智能指针只能用于指向堆空间中的内存
  • 智能指针的意义在于最大程序的避免内存问题

以上内容参考狄泰软件学院系列课程,请大家保护原创

脚本宝典总结

以上是脚本宝典为你收集整理的【C++】 37_智能指针分析全部内容,希望文章能够帮你解决【C++】 37_智能指针分析所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。