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?
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 .
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With