Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An operator == whose parameters are non-const references

I this post, I've seen this:

class MonitorObjectString: public MonitorObject {
    // some other declarations
    friend inline bool operator==(/*const*/ MonitorObjectString& lhs,
                                  /*const*/ MonitorObjectString& rhs)
    { return lhs.fVal==rhs.fVal; }
}

Before we can continue, THIS IS VERY IMPORTANT:

  • I am not questioning anyone's ability to code.
  • I am just wondering why someone would need non-const references in a comparison.
  • The poster of that question did not write that code.

This was just in case. This is important too:

  • I added both /*const*/s and reformatted the code.

Now, we get back to the topic:

I can't think of a sane use of the equality operator that lets you modify its by-ref arguments. Do you?

like image 356
pyon Avatar asked Feb 03 '26 23:02

pyon


2 Answers

Perhaps the classes use a form of lazy initialization. When the data is accessed, proper initialization must occur, and the data must be fetched. This may change class members.

However, lazy initialization can be formed so that modification to the class isn't necessary. This can be accomplished by using the Pimpl idiom (by a pointer to a private class) or by using the mutable keyword (not recommended!).

like image 65
strager Avatar answered Feb 05 '26 12:02

strager


Most likely they forgot the const. Operator overloads should behave consistently and not perform 'out of character' actions.

As a general rule, an equality operator should never modify any of the objects it is comparing. Declaring const enforces this at the compiler level. However, it is often left out. "Const correctness" is very often overlooked in C++.

like image 26
Andrew Rollings Avatar answered Feb 05 '26 12:02

Andrew Rollings



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!