You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用std::shared_ptr的use_count()时GDB触发RecursionError问题咨询

GDB调用std::shared_ptr::use_count()触发递归错误的原因与解决方法

这确实是GDB配套的libstdc++ Python调试扩展(xmethods)存在的Bug。从完整Python栈追踪可以看到,SharedPtrUseCountWorker的构造函数在第733行无限递归调用自身,最终触发Python的递归深度限制错误。

问题复现

以下脚本可稳定复现该问题:

cat << EOF > main.cc
#include <iostream>
#include <memory>

int main() {
    auto ptr = std::make_shared<int>(0);
    std::cout << ptr.use_count() << "\n";
    return 0;
}
EOF

g++ -std=c++17 -g main.cc
./a.out
gdb -q a.out -ex "set confirm off" -ex "b 7" -ex "r" -ex "p ptr.use_count()" -ex "q"

执行后GDB输出:

(gdb) p ptr.use_count()
Python Exception <class 'RecursionError'>: maximum recursion depth exceeded
Error while looking for matching xmethod workers defined in Python.

开启Python完整栈追踪后可见递归根源:

(gdb) set python print-stack full
(gdb) p ptr.use_count()
Traceback (most recent call last):
  File "/lib/x86_64-linux-gnu/../../share/gcc/python/libstdcxx/v6/xmethods.py", line 777, in match
    worker = method.worker_class(class_type.template_argument(0))
  File "/lib/x86_64-linux-gnu/../../share/gcc/python/libstdcxx/v6/xmethods.py", line 733, in __init__
    SharedPtrUseCountWorker.__init__(self, elem_type)
  File "/lib/x86_64-linux-gnu/../../share/gcc/python/libstdcxx/v6/xmethods.py", line 733, in __init__
    SharedPtrUseCountWorker.__init__(self, elem_type)
  File "/lib/x86_64-linux-gnu/../../share/gcc/python/libstdcxx/v6/xmethods.py", line 733, in __init__
    SharedPtrUseCountWorker.__init__(self, elem_type)
  [Previous line repeated 995 more times]
RecursionError: maximum recursion depth exceeded
Error while looking for matching xmethod workers defined in Python.

临时解决方法

  1. 禁用GDB的xmethods功能
    在GDB中执行以下命令后,即可正常调用use_count():

    set print xmethods off
    p ptr.use_count()
    

    或者直接访问shared_ptr的内部引用计数成员(适配Ubuntu22.04的libstdcxx版本):

    p ptr._M_use_count
    
  2. 升级GDB版本
    该Bug已在GDB 13及以上版本中被修复,可通过PPA或源码编译完成升级。

  3. 切换到LLDB调试
    如你测试的结果,LLDB对std::shared_ptr::use_count()的调用支持正常,可直接替代GDB完成调试工作。

内容的提问来源于stack exchange,提问作者techhara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:25:16