C++:移动构造函数和移动赋值运算符
与拷贝构造函数不同,移动构造函数不分配任何新内存;它接管给定的StrVec中的内存。在接管内存之后,它将给定对象中的指针都置为nullptr。这样就完成了从给的对象的移动操作,此对象将继续存在。最终,移后源对象会被销毁。 //移动构造函数 StrVec::StrVec(StrVec &&s) noexcept:elements(s.elements), first_free(s.first_free), cap(s.cap){ s.elements = nullptr; s.first_free = nullptr; s.cap = nullptr; } 移动赋值运算符执行与析构函数和移动构造函数相同的工作。类似拷贝赋值运算符,移动赋值运算符必须正确处理自赋值。 //移动赋值运算符 StrVec& StrVec::operator=(StrVec &&rhs) noexcept{ //直接检测自赋值:检测this指针与rhs的地址是否相同 if(this != &rhs){ free(); //释放已有元素 elements = rhs.elements; //从rhs接管资源 first_free = rhs.first_free; cap = rhs.cap; //将rhs置为可析构状态 rhs.elements = rhs.first_free = rhs.cap =