Displaying dereferenced STL iterators in gdb

放肆的年华 提交于 2019-12-02 19:32:31

Here is how i do it:

This GDB was configured as "i686-pc-linux-gnu"...
(gdb) list
1       #include <iostream>
2       #include <map>
3
4       int main()
5       {
6           std::map<int, int> a;
7           a[10] = 9;
8           std::map<int, int>::iterator it = a.begin();
9           ++it;
10      }
(gdb) b test.cpp:9
Breakpoint 1 at 0x8048942: file test.cpp, line 9.
(gdb) r
Starting program: /home/js/cpp/a.out

Breakpoint 1, main () at test.cpp:9
9           ++it;
(gdb) set print pretty on
(gdb) p it
$1 = {
  _M_node = 0x94fa008
}
(gdb) p *it
$2 = (class std::pair<const int, int> &) @0x94fa018: {
  first = 10,
  second = 9
}
(gdb)

You can use p (*it)->second

You can try Archer, a gdb development branch primarily dedicated to improving the C++ debugging experience. Click here to see the demo of pretty printer for C++. This new project also allows one to control gdb with python script. The primary developer, Tom Tromey, wrote quite a few blogs about this excited project.

I realize that this is an old question, but I think I've found the "best" answer to it yet. In searching around, I came across a .gdbinit file that dereferences the stl types very well. There are apparently many versions of this floating around, but this is the newest one that I've been able to find:

http://www.yolinux.com/TUTORIALS/src/dbinit_stl_views-1.03.txt

p will be an iterator to std::pair<const int, double>, so what you actually want is p->first. I don't think GDB handles overloaded operators well, though, so you probably want p.{some member that represents the pair object}.first. There is Doxygen documentation for libstdc++, so you can figure out what member you want, in this case it looks to be ((_Rb_tree_node<pair<const int, double> >*)(p._M_node))-> _M_value_field.first. Because this is pretty verbose, I would check to see if operator overloading works first (and no, I don't think there's anything simpler; sorry). You could also try explicitly calling operators, but I don't think gcc can do that either (e.g. it.operator*().first).

EDIT: wait, litb's post seems to show that gcc does support operator overloads on *. Weird, I always found that didn't work!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!