Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "Extending move semantics to *this" all about?

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!

like image 327
Khaled Alshaya Avatar asked Jan 08 '11 10:01

Khaled Alshaya


2 Answers

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
like image 70
UncleBens Avatar answered Oct 14 '22 20:10

UncleBens


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.

like image 43
fredoverflow Avatar answered Oct 14 '22 19:10

fredoverflow