Albert
Albert

Reputation: 1123

Rvalue reference losing its nature

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?

Upvotes: 0

Views: 88

Answers (2)

M.M
M.M

Reputation: 141598

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.

Upvotes: 1

Andreas DM
Andreas DM

Reputation: 10998

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

Upvotes: 1

Related Questions