• C++对象动态内存


    对象的动态内存分配

    Spread{
        int ** arr = new int*[10];
        for(int i=0;i<10;i++)
        {
            arr[i] = new int[10];
        }
        
        // 析构
        for(auto i=0;i<10;i++)
        {
            delete[] arr[i];
        }
        delete[] arr;
    }
    Spread s1(1,2), s2(3,4);
    

    内存空间:

    复制操作:-> 调用拷贝构造函数 (默认都是浅拷贝)

    s2 = s1;
    

    废弃的内存称为内存泄漏。

    复制对象时,调用拷贝构造函数

    拷贝构造函数

    class Spread
    {
    public:
        Spread(const Spread& s)
        {
            this->cells = new int* [10];
            for(int i=0;i<10;i++)
            {
                cells[i] = new int* [0];
            }
            for(int i=0;i<10;i++)
            {
                for(int j=0;j<10;j++)
                {
                    this->cells[i][j] = s.cells[i][j];
                }
            }
        }
    }
    

    重写赋值运算符

    class Spread
    {
    public:
        Spread& operator=(const Spread& s)
        {
            if(this == &s)
            {
                return *this;
            }
            // other operate
        }
    }
    

    只要动态分配了类内存,就必须重写拷贝构造、析构函数和复制运算符

    禁止赋值和按值传递

    当类中定义了动态内存,如果要禁止他人复制对象或者给对象复制,只需要显示的将operator=函数和拷贝构造方法定义为delete即可:

    class Spread
    {
    public:
        Spread& operator=(const Spread& s) = delete;
        Spread(const Spread& s) = delete;
    }
    
    Records::Employee emp = Records::Employee(); // 报错
    Records::Employee emp2;  // ok
    emp2.display();
    
    

    不同的数据类型成员

    静态成员|类成员

    1. 在成员函数中必须通过类名+::访问
    class Spread
    {
        static int port;
        public int getPort()
        {
            return Spread::port;
        }
    }
    
    

    const方法

    const方法不可以修改数据成员。

    class Spread
    {
        static int port;
        public int getPort() const;
        public int getPort() const
        {
            return Spread::port;
        }
    }
    
    

    mutable数据成员

    将数据成员定义为mutable,可以在const方法中修改

    mutable int num;
    

    内联方法

    编译器将函数体直接插入到方法调用的位置,称为内联函数

    inline Spread::getValue() const
    {
        return value;
    }
    

    对于将实现放在类中,实际上就是内联函数

  • 相关阅读:
    002变量
    001Java输入、eclipse快捷键
    040同步条件event
    kali配置ip,更新源,更新签名
    039条件变量同步(Condition)
    038信号量
    037多线程同步
    配置java环境变量(详细)
    提高你的Python能力:理解单元测试
    电影里的代码之《机械姬》:筛法求质数
  • 原文地址:https://www.cnblogs.com/zhuxiang1633/p/13235876.html
Copyright © 2020-2023  润新知