Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast void pointer to unique_ptr<T> in gdb?

I like to cast a void pointer back to unique_ptr<T> with arbitrary type T so that I can dereference it to the contents of it. But with the following simple example:

#include <memory>

class Foo {
public: Foo(){};
};

int main() {
  std::unique_ptr<Foo> p1 (new Foo);
  void *p2 = (void*)&p1;
  return 0;
}

I get the following error and not be able to cast:

$ gdb ./unique-ptr
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
...
(gdb) b 10
Breakpoint 1 at 0x400682: file unique-ptr.cc, line 10.
(gdb) run
Starting program: /home/vagrant/c-test/unique-ptr/unique-ptr

Breakpoint 1, main () at unique-ptr.cc:10
10        return 0;
(gdb) p p1
$1 = std::unique_ptr<Foo> containing 0x603010
(gdb) p p2
$2 = (void *) 0x7fffffffea40
(gdb) p *(std::unique_ptr<Foo>*)p2
A syntax error in expression, near `)p2'.
(gdb) 

Actual use case is that I like to print out contents of unique_ptr contained in container class, but this is the issue currently preventing me to go further.

like image 816
hshib Avatar asked Nov 17 '16 22:11

hshib


1 Answers

The actual type name created with the template is not std::unique_ptr<Foo>. Obtain the real type name with:

(gdb) ptype p1 
type = class std::unique_ptr<Foo, std::default_delete<Foo> > [with _Tp = Foo, _Dp = std::default_delete<Foo>] {
  private:
    __tuple_type _M_t;
...

From this, I figured out that gdb recognizes std::unique_ptr<Foo, std::default_delete<Foo> >, and I was able to do:

(gdb) p *(std::unique_ptr<Foo, std::default_delete<Foo> > *)p2
$3 = std::unique_ptr<Foo> containing 0x603010

which matches with

(gdb) p p1
$1 = std::unique_ptr<Foo> containing 0x603010
like image 101
hshib Avatar answered Nov 19 '22 07:11

hshib