我遇到过 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;
}
根据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/