#include <gmpxx.h>
int main() {
mpq_class a("1/-2");
mpq_class b("1/-3");
mpq_class c = a + b;
printf("%s\n", c.get_str().c_str());
}
根据 GMP 手册,当将无效表示字符串传递给构造函数时,应该会引发异常。然而,GMP 在这种情况下没有。
此外,尝试下面的代码,它会导致段错误:
#include <gmpxx.h>
class Container {
public:
mpq_class rat;
Container(mpq_class _rat) : rat(_rat) {}
};
int main() {
mpq_class a("1/-3");
Container *c = new Container(a);
}
这是一个错误吗? GMP 如此出名,我简直不敢相信它会这么容易崩溃。
最佳答案
您误解了手册,有理数的 C++ 接口(interface)部分开始于:
In all the following constructors, if a fraction is given then it should be in canonical form, or if not then `mpq_class::canonicalize' called.
这意味着如果您传入一个可以解析但不是规范形式的分数,那么您必须对其调用canonicalize
。
If the string is not a valid rational, an `std::invalid_argument' exception is thrown.
指的是字符串根本无法解析的情况。
可以说,文档在这方面可以更清楚。
关于c++ - 负分母让GMP崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145572/