2017-01-02 973 views
5

我有測試程序如下圖所示:如何在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的內部內容?

+0

你是什麼意思與*「在si商店」*? int''si的值指向? –

+0

[如何在GDB中訪問std :: tr1 :: shared \ _ptr的目標](https://stackoverflow.com/questions/24917556/how-to-access-target-of-stdtr1shared-ptr-in -gdb)| 'unique_ptr':https://stackoverflow.com/questions/22798601/how-to-debug-c11-code-with-unique-ptr-in-ddd-or-gdb –

回答

1

嘗試以下操作:

p *si._M_ptr 

現在,這個假設您正在使用libstdc++.so,給出的輸出p si

或者,你可以直接使用值0x614c20(從輸出):

p {int}0x614c20 

雙方應顯示值5

0

但如何獲取值存儲在它

您將有原始指針轉換爲存儲在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