Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an ampersand after this assignment operator mean?

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?

like image 606
Mihai Todor Avatar asked Sep 06 '12 18:09

Mihai Todor


People also ask

What does ampersand operator do?

The ampersand symbol & is used in C++ as a reference declarator in addition to being the address operator. The meanings are related but not identical. If you take the address of a reference, it returns the address of its target. Using the previous declarations, &rTarg is the same memory address as &target .

How do you write an assignment operator?

The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A.

Is assignment operator necessary?

If a class do not have any pointers, then we do not need to create assignment operator and copy constructor. C++ compiler creates copy constructor and assignment operator for each class. If the operators are not sufficient, then we have to create our own assignment operator.

Can appear on the left side of an assignment operator?

The term which appears on the left-hand side of the assignment operator (usually a variable) is called the 'target'. You will always assign a value to some variable but not to a constant.


1 Answers

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; 
like image 115
Nicol Bolas Avatar answered Sep 18 '22 06:09

Nicol Bolas