Chapter 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.

Solution

Short answer: In most cases, ...

Get Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.