Question

I was reading through this nice answer regarding the "Rule-of-five" and I've noticed something that I don't recall seeing before:

class C {
  ...
  C& operator=(const C&) & = default;
  C& operator=(C&&) & = default;
  ...
};

What is the purpose of the & character placed in front of = default for the copy assignment operator and for the move assignment operator? Does anyone have a reference for this?

Was it helpful?

Solution

It's part of a feature allowing C++11 non-static member functions to differentiate between whether they are being called on an lvalues or rvalues.

In the above case, the copy assignment operator being defaulted here can only be called on lvalues. This uses the rules for lvalue and rvalue reference bindings that are well established; this just establishes them for this.

In the above case, the copy assignment operator is defaulted only if the object being copied into can bind to a non-const lvalue reference. So this is fine:

C c{};
c = C{};

This is not:

C{} = c;

The temporary here cannot bind to an lvalue reference, and thus the copy assignment operator cannot be called. And since this declaration will prevent the creation of the usual copy assignment operator, this syntax effectively prevents copy-assignment (or move-assignment) to temporaries. In order to restore that, you would need to add a && version:

C& operator=(const C&) && = default;
C& operator=(C&&) && = default;

OTHER TIPS

It means that that function is only callable on lvalues. So this will fail because the assignment operator function is called on an rvalue object expression:

C() = x;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top