Item 38. Object Identity
Difficulty: 5
"Who am I, really?"
This problem addresses how to decide whether two pointers really
refer to the same object.
The "this != &other" test
(illustrated below) is a common coding practice intended to prevent
self-assignment. Is the condition necessary and/or sufficient to
accomplish this? Why or why not? If not, how would you fix it?
T& T::operator=( const T& other )
{
if( this != &other ) // the test in question
{
// ...
}
return *this;
}
Remember to distinguish between "protecting
against Murphy versus protecting against Machiavelli"—that is,
protecting against things going wrong on their own versus a
malicious programmer going to great lengths trying to break your
code.
|