this keyword and address object for operator=

I don't understand this part of the below code:

1
2
3
    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);
}
 
Last edited on
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

Next, the alternative is the well-known copy-and-swap idiom, which should be preferred:
https://chara.cs.illinois.edu/sites/cgeigle/blog/2014/08/27/copy-and-swap/
http://www.gotw.ca/gotw/059.htm

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

I recommend getting a better reference. :)
Last edited on
@mbozzi, I think we do not need perator& since it is operator= , but you are right if we face that kind of situation.

The other websites were a much better reference than the one I found. Thanks for mentioning them.
Topic archived. No new replies allowed.