Home >Backend Development >C++ >How to Avoid Infinite Recursion When Overloading the Equality Operator (==)?

How to Avoid Infinite Recursion When Overloading the Equality Operator (==)?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-08 16:01:41587browse

How to Avoid Infinite Recursion When Overloading the Equality Operator (==)?

Safely overload the equality operator (==) to avoid infinite recursion

When overloading the equality operator (==), be sure to handle null cases carefully to prevent infinite recursion. An infinite loop of == checks may result when one or both operands are empty.

To resolve this issue, please use the ReferenceEquals method instead of == to compare the null value of the object. This method returns true if both operands are null or if both operands refer to the same object, false otherwise. By using ReferenceEquals, the following code handles null values ​​accurately:

<code class="language-csharp">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 taking this approach, the == overloaded method can efficiently compare Foo objects (regardless of whether they are null) without triggering infinite recursion.

The above is the detailed content of How to Avoid Infinite Recursion When Overloading the Equality Operator (==)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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