diff --git a/gmp.c b/gmp.c index 9485fd03..cde6eeeb 100644 --- a/gmp.c +++ b/gmp.c @@ -33,7 +33,6 @@ MPZ_new(void) if (global.freelist_size) { res = global.freelist[--global.freelist_size]; (void)zz_set(0, &res->z); - Py_INCREF((PyObject *)res); } else { #endif @@ -607,16 +606,28 @@ new(PyTypeObject *type, PyObject *args, PyObject *keywds) return new_impl(type, arg, base); } +#ifdef ON_CPYTHON static void -dealloc(PyObject *self) +finalize(PyObject *self) { MPZ_Object *u = (MPZ_Object *)self; -#ifdef ON_CPYTHON if (global.freelist_size < MAX_FREELIST_SIZE && zz_sizeof(&u->z) <= MAX_FREELIST_SIZEOF && MPZ_CheckExact(self)) { + Py_INCREF(self); + } +} +#endif + +static void +dealloc(PyObject *self) +{ + MPZ_Object *u = (MPZ_Object *)self; + +#ifdef ON_CPYTHON + if (PyObject_CallFinalizerFromDealloc(self)) { global.freelist[global.freelist_size++] = u; } else { @@ -1949,6 +1960,9 @@ PyTypeObject MPZ_Type = { .tp_basicsize = sizeof(MPZ_Object), .tp_new = new, .tp_dealloc = dealloc, +#ifdef ON_CPYTHON + .tp_finalize = finalize, +#endif .tp_repr = repr, .tp_str = str, .tp_richcompare = richcompare,