这是 std::gcd 中的错误吗?
Is this a bug in std::gcd?
我发现 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.
还第一次来电returns2
。
我在这里错过了什么吗?
gcc 和 clang 都是这样。
看起来像是 libstdc++ 中的错误。如果将 -stdlib=libc++
添加到 CE 命令行,您将得到:
-120 120
10 10
10
10
我发现 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.
还第一次来电returns2
。
我在这里错过了什么吗?
gcc 和 clang 都是这样。
看起来像是 libstdc++ 中的错误。如果将 -stdlib=libc++
添加到 CE 命令行,您将得到:
-120 120
10 10
10
10