0

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;
}
cigien
  • 57,834
  • 11
  • 73
  • 112
Caiyi Zhou
  • 143
  • 1
  • 9

1 Answers1

1

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.

Luis Guzman
  • 996
  • 5
  • 8
  • If you had `string foo() { return ""; }` then you can `foo() = move(a);`. That doesn't do anything *useful*, but it is moving an lvalue onto an rvalue. – Caleth Mar 12 '21 at 15:01
  • @Caleth, not really because `move(a)` is technically an rvalue. If you try `foo() = a;`, `a` is an lvalue, but then it's a copy. In any case, like you said, it is not useful. – Luis Guzman Mar 12 '21 at 15:47
  • `move(a)` is an xvalue. It's the archetypical "both an lvalue and an rvalue" – Caleth Mar 12 '21 at 16:25