c++ - 在哪些情况下 std::optional operator == 会导致未定义的行为?

标签 c++ c++17 stdoptional

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.


这里让我感到困惑的是:
  • 这些格式不正确的比较的例子是什么?
  • 为什么编译器/STL 不拒绝无效的比较而不是给我们 UB?
  • 最佳答案

    这源于不精确的规范,此后已得到纠正。
    C++17 ,这些比较被指定为:

    Requires: The expression *x == *y shall be well-formed and its result shall be convertible to bool.


    Requires 是一个先决条件,因此不满足这些条件将是 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 (谢谢,编码(marshal)!)。用于指定标准库的新术语来自 Walter Brown 的“制定库语义规范指南”论文 (P1369)。

    关于c++ - 在哪些情况下 std::optional operator == 会导致未定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62535058/

    相关文章:

    c++ - 模板如何出现在翻译单元中?

    c++ - C、C++ 与 Python 的接口(interface)

    c++ - 使用 C 函数操作 std::string

    c++ - 为什么 std::string append 不会在 rval ref 上重载?

    c++ - 使用 std::optional 通过引用将 std::vector<int> 传递给函数

    c++ - QVector<int>[index] 返回另一个 QVector?

    c++ - (最好是提升)无锁数组/vector/ map /等?

    c++ - 什么时候适合使用 std::optional

    c++ - Q : How to define a nondiscard boolean in C++17, 最好使用枚举?

    c++ - 防弹 C++ 临时生命周期?