Problem with __gmp_expr

Marc Glisse marc.glisse at
Fri Jan 17 14:27:11 UTC 2014

On Fri, 17 Jan 2014, Niels Möller wrote:

> Marc Glisse <marc.glisse at> writes:
>> In gmp, -m*a is a neg
>> expr that stores a ref to a mult expr that stores references to m and
>> a. Since you managed to postpone the evaluation of the expression, the
>> mult expr went out of scope (older versions of gcc don't crash because
>> they are not good at reusing space from dead objects).
> I don't understand these things, but it sounds very brittle.

Well, expression template libraries all come with a big WARNING sign... 
This part of gmpxx has been this way since its creation (before I learnt 
C++), and people didn't complain that much. std::valarray in gcc's 
libstdc++ should have the same issues.

> If some
> usages are simply not supported by gmpxx, is there some way to either
> get a compile time error when a referenced expression goes out of scope,
> or at least some more *controlled* crash or assertion failure, without
> trashing random memory locations?

That doesn't seem easy. Maybe with a binary incompatible, invasive, debug 

Note that the patch I posted (I don't think we want it for 5.2, it needs 
more investigation) would make those cases valid. There would still be 
crashing operations like:
mpq_class f(void);
auto x=-f()+1;
because in this case we would need to store the number returned by f, and 
that can't be done cheaply as long as we don't have some form of lazy 
initialization. Or we could do in-place operations on rvalues, but that 
would also require a cheap move constructor (aka lazy init).

>> Other libraries would have a big neg expr that embeds a copy of the
>> mult expr,
> Now you're talking about copies of the expr objects used in the template
> machinery, not copies of the underlying numbers?

Yes, not the numbers (the part of the sentence you removed said that 
mp?_class is not copied).

Marc Glisse

More information about the gmp-bugs mailing list