move semantic/ r-value /L-value (copy from stakcoverflow)

class string{
    char* data;

public:
    string(const char* p){
        size_t  size =std::strlen(p)+1;
        data =new char[size];
    }
    ~string(){
        delete[] data;
    }

    string(const string& that){
        size_t  size = std::strlen(that.data)+1;
        data = new char[size];
        std::memcpy(data, that.data,size);
    }

    /// move semantic, that is a r-value to pass its data
    string(string&& that)   // string&& is an rvalue reference to a string
    {
        data = that.data;
        that.data = nullptr;
    }
};

 其中为什么要用到 string&& that 是因为如果要调用的话可能为:

string(x);

string(x+y)

string(string a)

如果用左值,不论怎么样都要深拷贝,所以用右值直接替换会比左值更快

posted @ 2019-09-09 23:55  Cullchestar  阅读(134)  评论(0编辑  收藏  举报