c++ - 负分母让GMP崩溃?

标签 c++ gmp

#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/

相关文章:

c++ - 如何专门化依赖于类的静态数据成员的模板?

math - GNU GMP mpz_powm() 不带 mod

c - 将 gdb 与 GMP 变量一起使用

python - GMPY2(或 GMP)是否具有 pow() 函数?

c++ - 如何在类中实现可选择的类似命名空间的功能?

c++ - QtGui4.lib(QtGui4.dll) : fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'

c# - 如何向 C# 库添加服务引用?

c++ - 使用 Visual Studio 构建 GMP 库?

python - mpz 变量的算术结果是什么?

c++ - 使用指针传递引用和值