首页 > 其他 > 详细

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

时间:2019-09-10 00:47:59      阅读:81      评论:0      收藏:0      [点我收藏+]
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)

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

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

原文:https://www.cnblogs.com/sunchuankai/p/11495088.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!