Home >Backend Development >C++ >How to Prevent Infinite Recursion When Overloading the == Operator with Null Values?
Handling null values when overloading the == operator
In some cases, trying to overload the == operator with the following code may result in infinite recursion:
<code class="language-c#">Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { return foo1 == null ? foo2 == null : foo1.Equals(foo2); }</code>
The problem is that without specific null checking, the == comparison recursively calls the == operator overloaded method to compare foo1 and foo2. Since foo1 is empty, a recursive loop is triggered.
To solve this problem, you can use ReferenceEquals
to add a null value check:
<code class="language-c#">Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (object.ReferenceEquals(null, foo1)) return object.ReferenceEquals(null, foo2); return foo1.Equals(foo2); }</code>
By using ReferenceEquals
to check for null values, you ensure that the == operator overloaded method does not recur infinitely, allowing null comparisons to be handled gracefully.
The above is the detailed content of How to Prevent Infinite Recursion When Overloading the == Operator with Null Values?. For more information, please follow other related articles on the PHP Chinese website!