C++ Logo


Advanced search

std::optional nullopt comparisons

From: Johan Williamsson <johan.williamsson_at_[hidden]>
Date: Mon, 24 Jun 2019 15:59:17 +0200
Hi, I was redirected here from isocpp.org for questions about the standard,
so I hope this is the right place to ask. Now to my question:

What's the rationale behind the decision to allow comparisons between
values and optional values without at least throwing an exception if the
optional value is not assigned?

I've seen this pattern as a source of sneaky bugs a few too many times now,
so I thought I should ask about it. Here's an example, where T may be a POD

T x = {};
std::optional<T> y = {};
bool z = x < y; // y may still not have been assigned a value

When is it meaningful to compare a possible nullopt with a value like this?
And are such cases common enough, or shouldn't the compiler or static
analysers at least warn about it?
Every time I've seen this it has been a programmer's mistake - it's easy to
forget writing ".value()".

Received on 2019-06-24 09:01:19