r/cpp • u/mcencora • May 11 '26
std::optional equality comparison operator seems broken for nested optionals
While chasing a bug in a program I found out that equality comparison operator T vs optional<T> is broken if T is optional<U>. It is broken in worst possible way - it compiles but for some values it returns wrong results!
Here is an example:
https://godbolt.org/z/v3bcTodGj
Since both sides of eq operator are specialization of optional then following overload is used:
operator==(const optional<T>& lhs, const optional<U>& rhs);
This operator is specified to returnlhs.has_value() != rhs.has_value() ? false :(lhs.has_value() == false ? true : *lhs == *rhs)
This falls apart for above scenario since lhs has value while rhs no value.
Since this is a case of optional<T>{} == T{} comparison, such scenario should be handled separately. Here is my attempt at fixing it:
https://godbolt.org/z/Yq3nM4xn4
This is rather not a proper fix, since it will still break for cases like optional<optional<short>>{} == optional<int>{}, and the internal if-constexpr instead should probably compare the nestedness of lhs and rhs optional.
I didn't check but most likely the same problem applies to relational operators.
Edit:std::expected seems to be affected as well:
While developer may expect following comparison to work std::expected<T, E>{} == T{} (thanks to the operator==(const expected&, const T2&) - it falls apart when T is expected<U> with unexpected value - because operator==(const expected&, const expected<T2, E2>&) overload is actually selected in that scenario.
https://godbolt.org/z/h4jYfjYco
Edit2:
I believe the proper fix for std::optional and std::expected should be to constrain following operatorsoperator==(const expected& lhs, const expected<T2, E2>& rhs)operator==(const optional<T>& lhs, const optional<U>& rhs)
to be applicable only when lhs and rhs have same nestedness levels.
14
u/rihya-sifu May 11 '26 edited May 11 '26
Based on the documentation, I would expect this behavior. See https://en.cppreference.com/cpp/utility/optional/operator_cmp :
Performs comparison operations on
optionalobjects.1-7) Compares two
optionalobjects,lhsandrhs. The contained values are compared (using the corresponding operator ofT) only if bothlhsandrhscontain values. Otherwise,lhsis considered equal torhsif, and only if, bothlhsandrhsdo not contain a value.lhsis considered less thanrhsif, and only if,rhscontains a value andlhsdoes not.In your example, std::optional<T> has a value, but std::optional<U> does not, so it would not be considered equal.
I agree that it's not intuitive at first glance, but I'd also reckon that any code depending on nested optionals should be reconsidered.
28
u/AKostur May 11 '26
I'm not sure I understand the problem. For the first godbolt, isn't that trying to compare
So it's trying to compare an optional which contains a value vs an optional that does not contain a value. Isn't that supposed to compare as unequal?
21
u/hungarian_notation May 11 '26 edited May 12 '26
I think the real issue here is nested
optional<optional<...optional<int>>>of arbitrary depth should not equaloptional<int>of a different depth in any case.If we're going to copy off Haskell's homework, we need to make sure we're copying everything down correctly.
Just ( Just x )is NOT comparable toJust x, and why would it be? Should a single-element vector compare equal to a scalar? Trying to compareJust ( Just x )withJust xis a compile time error.exhibit a
If we are going to have an comparison that implicitly
joins one side of the operator, it should at least have the same meaning asopt == std::make_optional(value). I'd argue that would also be bad, but at least it would be consistent.edit:
The issues I had with seeming non-transitive equality were mistaken. It's still the
optional.comp.with.toverloads at the crux of this issue though, though not from OP's perspective.Overload 1 is defined as:
This is the scene of the crime for OP. The base case for asymmetric empty optionals is that first conditional, and the second conditional catches the symmetric empties. Non-empty pairs of optionals, however, escape to a different overload as soon as one of them is fully dereferenced. For asymmetric non-empties, overloads 21 and 22 take up the task of recursively de-referencing the remaining optional.
For some reason I had it in my head that the C++26 change explicitly banning optionals from one half of each overload was relevant here, but in reality that only affects a very small set of optional types whose overloads were affected by changes elsewhere.
The fundamental issue is simply that std::optional's comparison operators are willing to unwrap unbalanced optionals iff they are both non-empty.
Most of the prior art in the static-typed space would compare asymmetric optionals as unequal. The O.G. implementation in Haskell won't even try. Rust will similarly throw a compiler error if you try to compare two asymmetric optionals, but will actually implicitly dereference ONE of the comparison values if you compare an optional against a non-optional value. Java can't tell the difference between different types of optionals at runtime, so it just returns false if they don't have the exact same structure. Etc. Etc.
Meanwhile, all the dynamic languages tend to implement this idiom as null-coalescing, giving them similar behavior to automatic dereferencing.
I think there's a valid discussion to be had over whether its better to flatten optionals under comparison or to compare asymmetric forms as unequal. Unfortunately, we're not having that discussion because C++ isn't doing either of those two things. It's doing a bizzare third thing, and that's my problem here.
7
u/chengfeng-xie May 12 '26 edited May 12 '26
See also Barry's post, Getting in trouble with mixed comparisons:
0
u/markt- May 11 '26
Show me a non contrived use case where you would need this
2
u/angry_cpp May 13 '26
It’s hard to be more broken than this:
This example on godbolt
1
u/drykarma May 12 '26
Oh my god. I spent a day on this once because it silently accepts this comparison, so I didn't understand why a program was producing a specific behavior when it shouldn't.
I think it should at least throw a warning, can't imagine anyone using this comparison intentionally
-6
u/Entire-Hornet2574 May 12 '26
Fairly normal, you made wrong assumption and you have to understand better operator==
you have optional of optional == optional
lhs.has_value() != rhs.has_value() => this is truelhs has value, rhs doesn't, it so simple.