Sunday, August 5, 2018

Why don't C++ compilers define operator== and operator!=?



I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free':




  • A default (empty) constructor

  • A copy constructor

  • A destructor


  • An assignment operator (operator=)



But it cannot seem to give you any comparison operators - such as operator== or operator!=. For example:



class foo
{
public:
std::string str_;
int n_;

};

foo f1; // Works
foo f2(f1); // Works
foo f3;
f3 = f2; // Works

if (f3 == f2) // Fails
{ }


if (f3 != f2) // Fails
{ }


Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?


Answer



The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison.



It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...