(二)c++11 移动构造与移动赋值
话不多说,先上代码
class Apple { public: Apple(){ str = nullptr; } Apple(const char *another){ if (another==nullptr){ str = new char[1]; *str ='\0'; }else{ str = new char[strlen(another.str)+1]; strcpy(str, another.str); } } // 拷贝构造 Apple(const Apple & another){ if (another.str!=nullptr){ str = new char[strlen(another.str)+1]; strcpy(str, another.str); } } // 移动构造 Apple(Apple && another) { if (another.str != nullptr){ str = another.str; another.str = nullptr; } } // 拷贝赋值 Apple & operator = (const operator & another) { if (this == &another) return *this; delete []this->str; // 或者 free(str); if (another.str!=nullptr){ int len = strlen(another.str); str = new char[len+1]; strcpy(str, another.str); return *this; } } // 移动赋值 Apple & operator = (Apple && another) { if (this != &another) reurn *this; delete []this->str; // 或者 free(str); str = another.str; another.str = nullptr; } private: char * str; };
做一个优秀的程序媛

浙公网安备 33010602011771号