• C++函数自动生成规则


    一个类的构造函数包括:

    • 默认构造函数(无参数构造函数)
    • copy构造函数
    • move构造函数

    相关的赋值操作符:

    • copy赋值操作符
    • move赋值操作符

    上述方法或者操作符,在某些情况下编译器都会自动生成:

    1. 没有定义任何一种构造函数,自动生成默认构造函数。
      1)如果有自定义的其他构造函数,需要手动添加默认构造函数;
      2)或者使用=default显示增加默认实现;
      3)否则编译报错。
    2. 定义copy构造函数,不会自动生成move构造函数。
      1)move构造可编译通过,会调用copy构造执行。
    3. 定义move构造函数,不会自动生成copy构造函数。
      1)此时,copy构造不能编译。
    4. copy构造和copy赋值,以及move构造和move赋值不互斥,定义了一个,不会阻止编译器自动生成另一个。

    一个类,成员类型,删除赋值构造,这个类的赋值构造也会默认删除。

    class Base {
    public:
        Base() {
            cout << "base ctor()\n";
        }
    
        Base(const Base& b) {
            cout << "base copy ctor()\n";
        }
    
        Base(Base&& b) noexcept {
            cout << "base move ctor()\n";
        }
    
        Base& operator=(const Base& b) {
            cout << "base copy =\n";
            return *this;
        }
    
        Base& operator=(Base&& b) noexcept {
            cout << "base move =\n";
            return *this;
        }
    
        ~Base() {
            cout << "base de-ctor\n";
        }
    };
    
    class Derive: public Base {
    public:
        Derive() {
            cout << "derive: default\n";
        }
    
        Derive(const Derive& d): Base{d} {
            cout << "derive: copy ctor\n";
        }
    
    //    Derive& operator= (const Derive& d) {
    //        cout << "derive: copy =\n";
    //            return *this;
    //    }
    
    //    Derive(Derive&& d): Base{move(d)} {
    //        cout << "derive: move ctor\n";
    //    }
    //    Derive& operator= (Derive&& d) {
    //        cout << "derive: move =\n";
    //        return *this;
    //    }
    
        ~Derive() {
            cout << "derive: de-ctor\n";
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
  • 相关阅读:
    模板方法模式
    好消息|又一省22年二建成绩查询时间公布
    WPF 控件专题 Separator控件详解
    linux网络编程之TCP协议编程
    Python 变量声明(2)
    nginx-QPS限制
    【Python】 - Python的内置函数isinstance()中的参数classinfo一共有多少种,可以判断多少种类型?
    PaddleSeg学习3——使用PP-LiteSeg模型对道路进行分割
    paddle 自定义数据集和预处理
    flume系列之:拦截器过滤数据
  • 原文地址:https://blog.csdn.net/yinminsumeng/article/details/131142868