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

How to view the internal data of a smart pointer inside 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
 = std::shared_ptr (count 1, weak 0) 0x614c20

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

尝试以下操作:

p *si._M_ptr

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

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

p {int}0x614c20

两者都应显示值 5

but how to get the value stored in it

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

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