(二)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;
};

    

 

posted @ 2020-05-14 11:32  欧阳图图的少年成长记  阅读(314)  评论(0)    收藏  举报