51

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?

Community
  • 1
  • 1
Mihai Todor
  • 8,014
  • 9
  • 49
  • 86

2 Answers2

39

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;
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Interesting... Is this implemented in any compiler? – Mihai Todor Sep 06 '12 at 18:39
  • 1
    @MihaiTodor: It's not in GCC yet [apparently](http://gcc.gnu.org/projects/cxx0x.html#rvalue-this), but Clang has [had it since 2.9](http://clang.llvm.org/cxx_status.html). It's commonly called "rvalue reference for `*this`" – Nicol Bolas Sep 06 '12 at 18:41
  • 1
    Throughout your post you're refering to the copy constructor, but the question is about copy assignment. – Dave S Sep 06 '12 at 18:48
13

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;
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212