if (this != &that) { //not checking self
this->~Test();
}
Why do we write check for this != &that ?
And what does -> this->~Test(); do? What do you call that -> notation ?
I also want to know what is the logic behind checking for 'this' keyword to be equal and not equal to the address of an object ? (I know the process is checking for self_assignment).
Reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
const Test& copy(const Test& that) {
if (this == &that) {
return *this
}
//otherwise construct new object and copy over
}
Test(const &that) {
copy(that);
}
Test& operator=(const Test& that) {
if (this != &that) { //not checking self
this->~Test();
}
copy(that);
}
First, an observation: the expression this != &that is not correct for objects with an overloaded operator&. The fact that this appears to be presented as acceptable in the general case is (another) bad sign. std::addressof exists for this purpose. http://en.cppreference.com/w/cpp/memory/addressof
Next, this Stack Overflow answer does a good job of explaining:
a.) in what cases the check is necessary; and
b.) why that check is a bad idea, or rather an indication of poor (esp. exception-unsafe) design http://stackoverflow.com/a/12015213
Finally this->~Test();
The arrow operator -> is the indirect member access operator. It is exactly equivalent to (syntactic sugar for) (*this).~Test();, which is an explicit call to the destructor of *this. http://en.cppreference.com/w/cpp/language/operator_member_access