Home > Backend Development > C++ > How to Avoid Infinite Recursion When Overloading the '==' Operator with Null Checks?

How to Avoid Infinite Recursion When Overloading the '==' Operator with Null Checks?

Barbara Streisand
Release: 2025-01-08 15:56:41
Original
351 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template