在哪些情况下 std::optional operator == 会导致未定义的行为?
In which cases does std::optional operator == cause undefined behavior?
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.
这里让我困惑的是:
这些格式不正确的比较示例是什么?
为什么不compilers/STL直接拒绝无效比较而不给我们UB?
这是由于规格不准确造成的,现已改正。
在 C++17 中,这些比较指定为:
Requires: The expression *x == *y
shall be well-formed and its result shall be convertible to bool
.
要求是前提条件,因此不满足这些条件将是 undefined behavior。但是有许多不同类型的“先决条件”——这是否意味着静态检查,这是否意味着如果不满足条件,则从重载集中删除运算符,这是否意味着实际的未定义行为?
在 C++20 中,这些被指定为:
Mandates: The expression *x == *y
is well-formed and its result is convertible to bool
.
如果不满足条件,means 程序格式错误。基本上,授权是 static_assert
(或等同物)。
所以是的,标准库有义务拒绝那些比较不存在或没有给你类似 bool
的类型。这实际上永远不会给你未定义的行为(如果没有这样的运算符,实现会做什么,从 /dev/random
中读一点?)但现在它更明确地指定了。
这些更改来自 Marshall Clow 题为“强制标准库”的一系列论文,这篇论文特别来自 P1460 (thanks, Marshall!). The new terminology for specifying the standard library comes from Walter Brown's "Guidelines for Formulating Library Semantics Specifications" paper (P1369)。
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.
这里让我困惑的是:
这些格式不正确的比较示例是什么?
为什么不compilers/STL直接拒绝无效比较而不给我们UB?
这是由于规格不准确造成的,现已改正。
在 C++17 中,这些比较指定为:
Requires: The expression
*x == *y
shall be well-formed and its result shall be convertible tobool
.
要求是前提条件,因此不满足这些条件将是 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 (thanks, Marshall!). The new terminology for specifying the standard library comes from Walter Brown's "Guidelines for Formulating Library Semantics Specifications" paper (P1369)。