Question

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?

Was it helpful?

Solution

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!).

OTHER TIPS

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

There's a more baffling problem with the issue you bring up.

If I have two MonitorObjectStrings that are already const, I can't use this equality function.

There's clearly no requirement for non-const args in this case and, like you, I wouldn't think there's any general case for it either.

However, it's certainly the case that const-correctness problems can push their way up from lower levels of the code, and if you can't correct them low-down, then you might have to work around them higher up. Perhaps that's what happened here at some point?

If you can't use const because you're modifying operands, you're badly misusing operator overloading.

If you can't use const because the implementation calls non-const functions, you really should clean those up, or at least provide const alternatives.

If you're calling into code you can't change which doesn't use const, I'd use the const anyway, use const_cast at the deepest available point, and comment it.

As Shmoopty pointed out, the operator is a lot less useful than it should be since it can't be used on const objects, even if only one of them is const. A numeric equality operator that wouldn't support "a == 5" would violate the Law of Least Astonishment in a big way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top