O'Reilly logo

Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions by Herb Sutter

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required