如何查看 gdb 内部智能指针的内部数据



我有如下测试程序:

#include<memory>
#include<iostream>
using namespace std;
int main()
{
    shared_ptr<int> si(new int(5));
    return 0;
}

调试它:

(gdb) l
1   #include<memory>
2   #include<iostream>
3   using namespace std;
4   
5   int main()
6   {
7       shared_ptr<int> si(new int(5));
8       return 0;
9   }
10  
(gdb) b 8
Breakpoint 1 at 0x400bba: file testshare.cpp, line 8.
(gdb) r
Starting program: /home/x/cpp/x01/a.out 
Breakpoint 1, main () at testshare.cpp:8
8       return 0;
(gdb) p si
$1 = std::shared_ptr (count 1, weak 0) 0x614c20

它只打印出si的指针类型信息,但是如何获取存储在其中的值(在本例中5)?调试过程中如何检查si的内部内容?

尝试以下操作:

p *si._M_ptr

现在,这假设您正在使用 libstdc++.so ,给定 p si 的输出。

或者,您可以直接使用值0x614c20(来自输出):

p {int}0x614c20

两者都应显示值5

但是如何获取存储在其中的值

您必须将原始指针转换为存储在 std::shared_ptr 中的实际指针类型。使用whatis了解实际的指针类型是什么。

(gdb) p si
$8 = std::shared_ptr (count 1, weak 0) 0x614c20
(gdb) whatis si
type = std::shared_ptr<int>
(gdb) p *(int*)0x614c20
$9 = 5

最新更新