Pregunta

#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());
}

According to GMP's Manual, when invalid representation string is passed to the constructor, an exception is supposed to raise. However GMP doesn't in this case.

Moreover, try the code below, which leads to Segfault:

#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);
}

Is it a bug? GMP is so well-known that I couldn't believe that it crashes so easily.

¿Fue útil?

Solución

You are misinterpreting the manual, the section on the C++ interface for rationals starts:

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.

That means that if you pass in a fraction that can be parsed, but is not in canonical form, then you must call canonicalize on it.

If the string is not a valid rational, an `std::invalid_argument' exception is thrown.

refers to the case that the string could not be parsed at all.

Arguably, the documentation could be clearer on that.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top