Home >Backend Development >C++ >How to Avoid Infinite Recursion When Overloading the '==' Operator with Null Checks?
Properly handle null checks to avoid infinite recursion in '==' operator overloads
When overloading the '==' operator, be sure to properly handle null checks to prevent infinite recursion. The code snippet provided in the question shows an incorrect approach:
<code>if (foo1 == null) return foo2 == null;</code>
This condition causes infinite recursion because the second call to == will again try to check if foo1 is empty, causing an infinite loop.
Correct code
To solve this problem and avoid infinite recursion, use object.ReferenceEquals
for null checking:
<code>if (object.ReferenceEquals(foo1, null)) return object.ReferenceEquals(foo2, null);</code>
This condition correctly handles the case where foo1 or foo2 (or both) is empty. Returns true if both operands are empty; returns false if one or both operands are not empty.
Full correction
The corrected code below incorporates this modification into the provided operator overload:
<code>public static bool operator ==(Foo foo1, Foo foo2) { if (object.ReferenceEquals(foo1, null)) return object.ReferenceEquals(foo2, null); return foo1.Equals(foo2); }</code>
With this change, operator overloading will be able to correctly handle null checks without causing infinite recursion.
The above is the detailed content of How to Avoid Infinite Recursion When Overloading the '==' Operator with Null Checks?. For more information, please follow other related articles on the PHP Chinese website!