i would like to know if the default implementation of the assignment operator checks for self assignment, and so which of those two implementation can be considered the closest to the default one:
class A{
int x;
public :
...
// first one
A& operator=(const A& a){
if(this != &a) x = a.x;
return *this;
}
// second one
A& operator=(const A& a){
x = a.x;
return *this;
}
}
I've searched for C++ standard but the only one that i can found is this but there is nothing about this
No, implementations do not check for "self":
https://en.wikipedia.org/wiki/Assignment_operator_(C%2B%2B)
The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type.
It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one.
The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).
Assignment operator does not check against self assignment. Therefore your second implementation is the closest to the default one.
I can not see any word in standard about any such optimization and it would be strange if attributes of my class would not be assigned by compiler generated operator in some cases. Imagine that some attribute assignment is user defined one and does some uncommon task. Compiler does not know that and IMO should call them even if I assign an object to itself.
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