In my code, I have a STL vector which holds pointers to objects. The reason why I coded like this is because I must manipulate the objects itself from different places.
std::vector<Object*> objects;
for (int i = 0; i < 10; i++) {
Object* o = new Object(i);
objects.push_back(o);
}
This code is assuming that Object is an object which takes in an integer as a constructor parameter. Assuming that I breakpoint with my GDB after the for loop ends, what do I have to do in order to view the objects within my vector easily?
When I do "p objects" it only lists the pointer addresses which is totally expected, but I want to see the integer variable that each object holds as well. I tried "p objects[0]" but this returns "Could not find operator[]".
Has anyone ran into this problem? or know how I can get around this? My goal is to be able to look inside what objects actually hold from GDB when those object's pointers are stored in a STL vector.
This is certainly implemented defined, but for GCC, you can do:
print **(v._M_impl._M_start)@1
Where v
refers to the vector, and 1
refers to the index. You need to dereference twice to get the value.
struct Object
{
int n;
Object(int n)
: n(n) { }
};
int main()
{
std::vector<Object*> v;
v.push_back(new Object{42});
v.size(); // where we breakpoint
// release our memory at some point
}
And our test run:
(gdb) break 16
Breakpoint 1 at 0x400aae: file test.cpp, line 16.
(gdb) run
Starting program: a.out
Breakpoint 1, main () at test.cpp:16
16 v.size(); // where we breakpoint
(gdb) print v
$1 = {<std::_Vector_base<Object*, std::allocator<Object*> >> = {
_M_impl = {<std::allocator<Object*>> = {<__gnu_cxx::new_allocator<Object*>> = {<No data fields>}, <No data fields>}, _M_start = 0x604030, _M_finish = 0x604038, _M_end_of_storage = 0x604038}}, <No data fields>}
(gdb) print **(v._M_impl._M_start)@1
$2 = {{n = 42}}