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;
    }
  • 相关阅读:
    [转帖]能感动天地的老人,你拿什么来感动CCTV
    SaaS, 8,9点的太阳
    ERP软件开源是中国软件行业未来之路
    觉得为时已晚的时候,恰恰是最早的时候。
    新画皮故事——ERP软件为什么要免费
    如何定制SharePoint“欢迎”菜单?
    软件产品在什么情况下一定要走精品路线
    我的blogs
    测试环境中安装sharepoint server 2010过程中出现的一些问题及解决过程
    windows server 2008 与windows server 2008 r2区别
  • 原文地址:https://www.cnblogs.com/qiumingcheng/p/15483559.html
Copyright © 2011-2022 走看看