类的构造、移动、赋值函数示例

#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;         }     }
    // 这个函数尽量不提供,如果需要提供,则需要深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; }
上一篇:Day 30


下一篇:Bug现形记(一):一个多重继承程序的查错