c++ - 这是 std::gcd 中的错误吗?

标签 c++ language-lawyer c++17 unsigned libstdc++

我遇到过 std::gcd 的这种行为我发现意想不到的:

#include <iostream>
#include <numeric>

int main()
{
    int      a = -120;
    unsigned b =  10;

    //both a and b are representable in type C
    using C = std::common_type<decltype(a), decltype(b)>::type;
    C ca = std::abs(a);
    C cb = b;
    std::cout << a << ' ' << ca << '\n';
    std::cout << b << ' ' << cb << '\n';

    //first one should equal second one, but doesn't
    std::cout << std::gcd(a, b) << std::endl;
    std::cout << std::gcd(std::abs(a), b) << std::endl;
}

Run on compiler explorer

根据cppreference两次调用 std::gcd应该产生 10 ,因为所有先决条件都满足。

特别是,仅要求两个操作数的绝对值能够以其共同类型表示:

If either |m| or |n| is not representable as a value of type std::common_type_t<M, N>, the behavior is undefined.

但是第一个调用返回 2 。 我在这里错过了什么吗? gcc 和 clang 都是这样的。

最佳答案

看起来像是 libstc++ 中的错误。如果将 -stdlib=libc++ 添加到 CE 命令行,您将得到:

-120 120
10 10
10
10

关于c++ - 这是 std::gcd 中的错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59379703/

相关文章:

c++ - 在openCV中访问某些像素RGB值

c++ std::bad_alloc on std::filesystem::path 追加

c++ - 数组类型的 typedef 语法是什么?

c++ - 运算符方法是否占用 C++ 对象中的内存?

c++ - 为什么不能通过直接初始化语法来初始化类数据成员?

c++ - 是否允许编译器评估静态断言中的重言式

c++ - Lambda 自身返回 : is this legal?

c++ - 从另一个 std::Optional 和其他东西初始化 std::Optional 的惯用方法

c++ - rand() 每次运行程序时返回相同的数字

c++ - c++ 标准是否保证堆栈展开并出现异常?