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()
     
     
    主要记录的是学习听课的笔记
  • 相关阅读:
    Yield Usage Understanding
    Deadclock on calling async methond
    How to generate file name according to datetime in bat command
    Run Unit API Testing Which Was Distributed To Multiple Test Agents
    druid的关键参数+数据库连接池运行原理
    修改idea打开新窗口的默认配置
    spring boot -thymeleaf-url
    @pathvariable和@RequestParam的区别
    spring boot -thymeleaf-域对象操作
    spring boot -thymeleaf-遍历list和map
  • 原文地址:https://www.cnblogs.com/chengeputongren/p/12234826.html
Copyright © 2011-2022 走看看