Derek 朕會功夫
Derek 朕會功夫

Reputation: 94339

Accessing vector items in GDB

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?

Upvotes: 5

Views: 11728

Answers (3)

Linhb
Linhb

Reputation: 1

template <> Foo* &std::vector<Foo*>::operator[](size_type n) noexcept
{
    return this->begin()[n];
}

to use vector operator[], need the Template materialization

Upvotes: 0

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94339

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

For example,

template class std::vector<double>;

Upvotes: 3

Tom
Tom

Reputation: 51

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 [email protected]() 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

Upvotes: 5

Related Questions