What does an ampersand after this assignment operator mean?
Asked Answered
F

2

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?

Fonsie answered 6/9, 2012 at 18:29 Comment(5)
Compiler error on GCC 4.7.1. I've never heard of putting an ampersand there.Concinnous
Read the last comment to that answer.Unhopedfor
@JoachimPileborg Indeed, but I wasn't sure what to make of it, so I preferred to ask.Fonsie
For completeness sake, check out What is "rvalue reference for *this"?.Kliman
The rvalue reference for *this is implemented from gcc 4.8.1 onwards.Lipsey
M
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;
Misjudge answered 6/9, 2012 at 18:36 Comment(3)
Interesting... Is this implemented in any compiler?Fonsie
@MihaiTodor: It's not in GCC yet apparently, but Clang has had it since 2.9. It's commonly called "rvalue reference for *this"Misjudge
Throughout your post you're refering to the copy constructor, but the question is about copy assignment.Koster
E
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;
Exine answered 6/9, 2012 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.