2

I am primarily trying to understand the uses that this feature enables or facilitates. I understand which calls go where in the following:

struct Foo
{
   void bar() & {std::cout << "l-value"; }
   void bar() && {std::cout << "r-value"; }
};

Foo f;
f.bar();     // calls l-value version
Foo().bar(); // call r-value version

But what is the practical use of such a distinction?

CppNoob
  • 2,322
  • 1
  • 24
  • 35
  • 1
    You can choose different behaviour when you know that an object you're calling a function on is a temporary and will be destroyed soon (such as moving some resource out of it instead of making a deep copy). There are some examples in [this SO thread.](http://stackoverflow.com/questions/8610571/what-is-rvalue-reference-for-this) – jrok Mar 26 '14 at 10:45
  • @jrok Thanks. I understood that I can choose different behaviours - was trying to understand what those behaviours would be and what would it enable me to do. The answer by JohannesD in the thread you pointed is really useful. It answered a question on another thread [link]http://stackoverflow.com/questions/20717180/in-c-what-categories-lvalue-rvalue-xvalue-etc-can-expressions-that-prod. – CppNoob Mar 26 '14 at 10:49

1 Answers1

2

An rvalue method may safely move from or otherwise invalidate the invocant, because it won't be accessible afterwards (it must not return or store the reference, of course). So in cases where a destructive implementation of some operation is more efficient, you can provide it for rvalues only where it is safe to use. Moving from also comes into consideration for cast operators.

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172