0
votes

As is known to all that c++ std::move would steal internal content if used with non-fundamental type. I suddenly have a brainwave that what will happen to rvalue if move a lvalue to it. I initially thought it would still steal the content. But nothing happened,a has its string still. Does this caused by ignoring the move constructor? But I think a named rvalue is deemded by compiler to be lvalue, right?

int main()
{
    string a="4";
    string&& c = move(a);
    cout<<a<<endl;
}
1
std::move is a cast. It doesn' t steal anything. A move constructor or a move assignment operator do that. Your code doesn't invoke either. - n. 1.8e9-where's-my-share m.

1 Answers

1
votes

It is because c is declared as a reference (rvalue reference) to a. It is not a different string. In order to "still" (i.e. call the move constructor), c needs to be declared a string. Then, string a is "moved" to string c:

int main()
{
    string a="4";
    string c = move(a);
    cout<< "a :" <<a << ":" <<endl;
    
    cout << "c :" << c << ":"<< endl;
}

Output is:

a ::                                                                                                                                           
c :4:

This code moves an rvalue to an lvalue though, which is the way it's supposed to work. However, it sounds like you're trying to move an lvalue to an rvalue, but that is not what you're doing. c is an rvalue, but move(a) is also an rvalue. std::move() casts a to an rvalue reference. Think of a reference as something similar to a pointer, it is not a string. You can't move or copy a string to it. It just refers to the string. Anyway, I don't think that you can move lvalues to rvalues. I can't think of any case.