Question

Please, could someone explain in plain English what is "Extending move semantics to *this"? I am referring to this proposal. All what am looking for is what is that & why do we need that. Note that I do understand what an rvalue reference is in general, upon which move semantics is built. I am not able to grasp what such an extension adds to rvalue references!

Was it helpful?

Solution

The ref-qualifier feature (indicating the type of *this) would allow you to distinguish whether a member function can be called on rvalues or lvalues (or both), and to overload functions based on that. The first version gives some rationale in the informal part:

Prevent surprises:

struct S {
  S* operator &() &;            // Selected for lvalues only
  S& operator=(S const&) &;     // Selected for lvalues only
};

int main() {
  S* p = &S();                  // Error!
  S() = S();                    // Error!
}

Enable move semantics:

class X {
   std::vector<char> data_;
public:
   // ...
   std::vector<char> const & data() const & { return data_; }
   std::vector<char> && data() && { return data_; } //should probably be std::move(data_)
};

X f();

// ...
X x;
std::vector<char> a = x.data(); // copy
std::vector<char> b = f().data(); // move

OTHER TIPS

For example, you can overload operators as free functions with rvalue references if you wish:

Foo operator+(Foo&& a, const Foo& b)
{
    a += b;
    return std::move(a);
}

To achieve the same effect with a member function, you need the quoted proposal:

Foo Foo::operator+(const Foo& b) &&   // note the double ampersand
{
    *this += b;
    return *this;
}

The double ampersand says "this member function can only be called on rvalues".

Whether or not you must explicitly move from *this in such a member function is discussed here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top