3

For example, I have such struct in a templated class:

struct Foo{
    int data;
    vector<Foo*> children;
}

And to print out the data value, I can simply do this: (let bar be a pointer to a Foo)

print bar->data

and this works fine. However I would like to also follow children to another Foo. I tried:

print bar->children[0]->data

but it doesn't work. How should I access the items in a vector and use it in print?

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247

3 Answers3

5

With GDB 7.9 and g++ 4.9.2, it works quite well while printing bar->children[0]->data.

But, here is also an indirect method to access these elements: print (*(bar->children._M_impl._M_start)@bar->children.size())[0]->data where VECTOR._M_impl._M_start is the internal array of VECTOR and POINTER@VECTOR.size() is used for limiting the size of a pointer.

reference: How do I print the elements of a C++ vector in GDB?

Complement:

There is also another not so elegant but more general way:

print bar->children[0]

and you might get something like this:

(__gnu_cxx::__alloc_traits<std::allocator<Foo*> >::value_type &) @0x603118: 0x603090

so you can access to it with the pointer given above: print ((Foo)*0x603090).data

Community
  • 1
  • 1
Tom
  • 51
  • 2
2

With help from this answer, explicitly instantiating the vector fixes the problem.

For example,

template class std::vector<double>;
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
0
template <> Foo* &std::vector<Foo*>::operator[](size_type n) noexcept
{
    return this->begin()[n];
}

to use vector operator[], need the Template materialization

Delgan
  • 18,571
  • 11
  • 90
  • 141
Linhb
  • 1
  • 1