简体   繁体   中英

About std::move behavior

I played a little with std::move and I noticed something strange:

string && foo(string && x) {
    string && a = move(x);
    return move(a); //both x and a = "asdfgh"
}

int main(){

    string x,aa;

    aa = "asdfgh";
    x = foo(move(aa)); 
    //aa = "", x = "asdfgh" 

    aa = "asdf";
    x = move(aa); 
    //aa = "", x ="asdf"
}

The behavior in main is clear but why in foo after the move was called, x is not empty? Why it didn't "steal" from x ?

Because, in foo , a is a r-value reference . a and local variable x are the same object.

See this code :-

int main()
{

    string aa;
    aa = "asdf";
    string &&x = move(aa); 
    x[0]='b';
    cout<<boolalpha<<aa<<'\t'<<aa.empty()<<'\n';
    string y = move(aa);
    y[0]='c';
    cout<<aa<<'\t'<<aa.empty()<<'\n';
    return true;
}

Output :-

bsdf        false
            true

Clearly x is an rvalue reference to aa & not a different object (which is why on changing x there was a change in aa ). Hence aa wasn't emptied. However on the other hand y is a different object from aa & hence the std::move statement emptied aa .

Hence, a similar behaviour is shown by your code in the foo function. As x & a in foo are rvalue references to aa , your code doesn't empty aa .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM