【问题标题】:How to view the internal data of a smart pointer inside gdb?如何查看gdb内部智能指针的内部数据?
【发布时间】:2017-05-16 04:55:59
【问题描述】:

我有如下测试程序:

#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的内部内容?

【问题讨论】:

标签: c++ linux printing gdb shared-ptr


【解决方案1】:

尝试以下方法:

p *si._M_ptr

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

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

p {int}0x614c20

两者都应该显示值5。

【讨论】:

    【解决方案2】:

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

    您必须将原始指针转换为存储在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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-22
      • 2017-02-16
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多