zoukankan      html  css  js  c++  java
  • 类的构造、移动、赋值函数示例

    #include <iostream>
    using namespace std;

    class Teacher {
       public:
        int id;
        int* studentIds{nullptr};
        int count;

       public:
        Teacher(int id, int count) {
            this->id = id;
            this->count = count;
            this->studentIds = new int[count];
        }

        Teacher(Teacher&& other) {
            this->id = other.id;
            this->count = other.count;
            this->studentIds = other.studentIds;
            other.studentIds = nullptr;
        }

        // copy构造函数尽量不给出实现,如果不给出,因为提供了移动copy,所以这个函数是不允许调用的
        // Teacher(Teacher& other) {
        //     this->id = id;
        //     this->count = count;
        //     this->studentIds = other.studentIds; //这里简单这么实现,通常需要深copy,否则可能出现内存被重复释放的问题
        // }

        Teacher& operator=(Teacher&& other) {
            if (this->studentIds) {
                delete this->studentIds;
            }
      this->id = other.id;
           this->count = other.count;
           this->studentIds = other.studentIds;
        }

        // 这个函数尽量不提供,如果需要提供,则需要深copy,因为出现了移动赋值,如果不提供改函数,该函数是不允许使用的
        // Teacher& operator=(Teacher& other) {

        // }
        ~Teacher() {
            if (this->studentIds) {
                delete this->studentIds;
                this->studentIds = nullptr;
            }
        }
    };

    Teacher GetTeacher() {  // 借助了移动copy构造函数的能力,相当于返回了局部变量
        Teacher t(1, 4);
        for (int i = 0; i < t.count; i++) {
            t.studentIds[i] = i;
        }
        return t;
    }

    int main(int argc, char const* argv[]) {
        Teacher p = GetTeacher();

        cout << p.id << " " << p.count << endl;
        for (int i = 0; i < p.count; i++) {
            cout << p.studentIds[i] << " ";
        }
        cout << endl;
        return 0;
    }
  • 相关阅读:
    django 重建一个表
    近期数据工作的知识点总结(model-dict高级用法)
    搬运django中文网 CentOS7下部署Django项目详细操作步骤(django安装网站有时候打不开,备份用)
    创建ftp免密只读用户(外系统读取csv共享数据)
    某某系统从外部基础库读取数据
    离线安装 django-axes
    django queryset用法总结二
    django queryset用法总结一
    nginx 启动,停止 重启
    安装安全狗失败 ,linux wget的时候不去找目标ip,而是路由到其他ip,原因分析
  • 原文地址:https://www.cnblogs.com/qiumingcheng/p/15483559.html
Copyright © 2011-2022 走看看