Home > Backend Development > C++ > How to Prevent Infinite Recursion When Overloading the == Operator with Null Values?

How to Prevent Infinite Recursion When Overloading the == Operator with Null Values?

DDD
Release: 2025-01-08 16:07:41
Original
758 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template