0

I don't understand the following:

class Class {
  public:
  void operator=(string&&) {
      cout << "here";
  }
};

string func() {
    return "Paul";
}

int main()
{
    string&& rvalueref = func();

    Class obj;
    obj = rvalueref; <- error! Why isn't rvalueref a rvalue ref anymore?

    return 0;
}

since I can bind a prvalue to a rvalue reference, I thought I could also pass it around. Why does the above fail?

Albert
  • 1,085
  • 2
  • 10
  • 20
  • 4
    `rvalueref` is an lvalue. Rvalue references don't bind to lvalues. – chris Apr 23 '15 at 19:31
  • @chris Did you mean to say lvalues don't bind to rvalue references? – David G Apr 23 '15 at 19:34
  • @0x499602D2, I've likely been going off of [this title](http://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object) the entire time. Or compiler errors like *non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'* – chris Apr 23 '15 at 19:37
  • rvalueref is an lvalue?? But I just declared it a rvalue reference! – Albert Apr 23 '15 at 19:38
  • @Albert, Its type is rvalue reference to `int`. Its value category is lvalue. – chris Apr 23 '15 at 19:38
  • @Albert: It's an lvalue with an rvalue reference type... confusing, I know. You need to say `obj = std::move(rvalueref)` for it to get its 'rvalue-ness' back. – AndyG Apr 23 '15 at 19:39
  • @chris: I think you mean `std::string`, not `int` – AndyG Apr 23 '15 at 19:40

2 Answers2

1

I believe std::move is what you're looking to use. (defined in<utility>)
That way you can turn the lvalue into an rvalue.

//...
int main()
{
    string&& rvalueref = func();

    Class obj;
    obj = std::move(rvalueref);

    return 0;
}

If you wish to read more about it, information about the move semantics and rvalue references can be found here

Andreas DM
  • 10,685
  • 6
  • 35
  • 62
1

The "rvalue" in "rvalue reference" is talking about what the reference can bind to. Once it is bound, it's just a reference. There's no difference between a bound rvalue reference and a bound lvalue reference.

Named variables are lvalues. ("variable" means object or reference). To produce an xvalue, i.e. an expression with rvalue reference type, you will have to use std::move or equivalent.

M.M
  • 138,810
  • 21
  • 208
  • 365