[PATCH v2 5/9] gdb/python: allow ref_ptr<T, Policy>::new_reference to accept subclasses of T

Matthieu Longo
2026-03-03T16:20:27Z

When ref_ptr<T,Policy>::new_reference() is specialized for 'PyObject'
(i.e. gdbpy_ref<>), it currently requires the argument type to be exactly
'PyObject *'. As a result, pointers to subclasses of 'PyObject' must be
explicitly cast before being passed, making call sites unnecessarily
verbose.

This patch makes ref_ptr<T,Policy>::new_reference() a template method
that accepts both T and subclasses of T, performing the cast to 'T *'
internally when needed. This removes redundant casts at call sites
without changing behavior.
---
gdb/python/py-inferior.c | 2 +-
gdbsupport/gdb_ref_ptr.h | 5 ++++-
2 files changed, 5 insertions(+), 2 deletions(-)

diff --git a/gdb/python/py-inferior.c b/gdb/python/py-inferior.c
index ae309620e1f..e959a107858 100644
--- a/gdb/python/py-inferior.c
+++ b/gdb/python/py-inferior.c
@@ -400,7 +400,7 @@ infpy_threads (PyObject *self, PyObject *args)

for (const thread_map_t::value_type &entry : *inf_obj->threads)
{
- auto thr = gdbpy_ref<>::new_reference ((PyObject *) entry.second.get ());
+ auto thr = gdbpy_ref<>::new_reference (entry.second.get ());
if (PyTuple_SetItem (tuple.get (), i++, thr.release ()) < 0)
return nullptr;
}
diff --git a/gdbsupport/gdb_ref_ptr.h b/gdbsupport/gdb_ref_ptr.h
index 3d01bf4441b..647ac42367d 100644
--- a/gdbsupport/gdb_ref_ptr.h
+++ b/gdbsupport/gdb_ref_ptr.h
@@ -150,9 +150,12 @@ class ref_ptr
}

/* Acquire a new reference and return a ref_ptr that owns it. */
- static ref_ptr<T, Policy> new_reference (T *obj)
+ template <class TObj>
+ static ref_ptr<T, Policy> new_reference (TObj *obj)
{
Policy::incref (obj);
+ if constexpr (std::is_base_of<T, TObj>::value)
+ return ref_ptr<T, Policy> (static_cast<T *> (obj));
return ref_ptr<T, Policy> (obj);
}

--
2.53.0