zoukankan      html  css  js  c++  java
  • 智能指针

    • 内存泄露(臭名昭著的BUG)
    1. 动态申请堆空间,用完后不归还
    2. C++语言中没有垃圾回收机制
    3. 指针无法控制所指堆空间的生命周期
    • 我们需要什么?
    1. 需要一个特殊的指针
    2. 指针生命周期结束时主动释放堆空间
    3. 一片堆空间最多只能由一个指针标识
    4. 杜绝指针运算和指针比较(可以避免野指针)
    • 解决方法
    1. 指针操作符(->和*)
    2. 只能通过类的成员函数重载
    3. 重载函数不能使用参数
    4. 只能定义一个重载函数
    • 小结:
    1. 指针操作符(->和*)可以被重载
    2. 重载操作符能够使用对象代替指针
    3. 智能指针只能用于指向堆空间的内存
    4. 智能指针的意义在于最大程度的避免内存问题
    智能指针使用军规:只能用来指向堆空间中的对象或者变量
    #include <iostream>
    #include <string>
    using namespace std;
    class Test
    {
        int i;
    public:
        Test(int _val)
        {
            this->i = _val;
            cout << "Test(int _val)" << endl;
        }
        ~Test()
        {
            cout << "~Test()" << endl;
        }
        int get_value()
        {
            return i;
        }
    };
    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;
        }
        ~Pointer()
        {
            delete mp;
        }
        //如果mp等于NULL,返回true:1
        bool isNULL()
        {
            return (mp==NULL);
        }
    };
    int main()
    {
        cout << "Hello World!
    " <<endl;
        //使用类对象来代替指针,在变量p(对象)生命周期结束时
        //执行析构函数,释放变量mp
        Pointer p = new Test(6);
        cout << p->get_value() << endl;
        Pointer p1 = p;
        cout << p.isNULL() << endl;
        cout << p1->get_value() << endl;
    }
    运行结果:
    Hello World!
    Test(int _val)
    6
    1
    6
    ~Test()
     
     
    主要记录的是学习听课的笔记
  • 相关阅读:
    Min_25筛
    POJ-1068 Parencodings---模拟括号的配对
    POJ-3295 Tautology---栈+表达式求值
    POJ-2586 Y2K Accounting Bug贪心,区间盈利
    POJ-1328 Radar Installation--区间选点问题(贪心)
    POJ-2965 The Pilots Brothers' refrigerator---思维题
    POJ-1753 Flip Game---二进制枚举子集
    南阳OJ-2-括号配对问题---栈的应用
    hdu-1082 Matrix Chain Multiplication---栈的运用
    hdu-1237 简单计算器---中缀表达式转后缀表达式
  • 原文地址:https://www.cnblogs.com/chengeputongren/p/12234826.html
Copyright © 2011-2022 走看看