Cppreference具有以下对 std::optional
的混合(可选和一些其他非可选类型)比较运算符的描述:
Compares opt with a value. The values are compared (using the corresponding operator of T) only if opt contains a value. Otherwise, opt is considered less than value. If the corresponding two-way comparison expression between *opt and value is not well-formed, or if its result is not convertible to bool, the behavior is undefined.
这里让我感到困惑的是:
最佳答案
这源于不精确的规范,此后已得到纠正。
在 C++17 ,这些比较被指定为:
Requires: The expression
*x == *y
shall be well-formed and its result shall be convertible tobool
.
Requires 是一个先决条件,因此不满足这些条件将是 undefined behavior .但是有许多不同类型的“前提条件” - 这是否意味着静态检查,这是否意味着如果条件不满足,则从重载集中删除运算符,是否意味着实际未定义的行为?
在 C++20 ,这些被指定为:
Mandates: The expression
*x == *y
is well-formed and its result is convertible tobool
.
其中means如果不满足条件,程序就是格式错误的。基本上,授权是
static_assert
(或等效的)。所以是的,标准库有义务拒绝比较不存在或不给你类似
bool
的类型的类型。 .这实际上永远不会给您未定义的行为(如果没有这样的运算符,实现会做什么,从 /dev/random
中读取一点?)但现在它更明确地指定。这些更改来自 Marshall Clow 题为“强制标准库”的一系列论文,这篇文章特别来自 P1460 (谢谢,编码(marshal)!)。用于指定标准库的新术语来自 Walter Brown 的“制定库语义规范指南”论文 (P1369)。
关于c++ - 在哪些情况下 std::optional operator == 会导致未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62535058/