简体   繁体   English

C ++:如何查看vptr / vtable内容

[英]C++: How to look at vptr/ vtable contents

Every C++ object that has a virtual function has a vptr that points to a vtable. 每个具有虚函数的C ++对象都有一个指向vtable的vptr。 How can I see what this vptr is, and the contents it is point to? 我如何查看该vptr是什么以及其指向的内容? I understand this is compiler dependent and it could put vptr anywhere in the object memory space. 我知道这是依赖于编译器的,它可以将vptr放在对象存储空间中的任何位置。 But is there anyway I can find what it is? 但是无论如何,我能找到它吗?

Cheers. 干杯。

In this specific case, C has one vtable and A and B have none. 在这种特定情况下,C有一个vtable,而A和B没有。 You can see this for yourself by out-of-lining C's member functions, so that the vtable will actually be emitted, and correcting the other compile errors: extern "C" int puts(const char *); 您可以通过不使用C的成员函数来自己查看此情况,以便实际发出vtable并更正其他编译错误:extern“ C” int puts(const char *);

struct A { virtual void func_1() = 0; };
struct B { virtual void func_2() = 0; };

struct C : A, B
{
  void func_1();
  void func_2();
};

... compiling to an object file, and then looking at the symbols: ...编译为目标文件,然后查看符号:

$ gcc -c test.cc
$ nm test.o | c++filt
                 U puts
0000000000000000 T C::func_1()
000000000000001a T C::func_2()
0000000000000033 T non-virtual thunk to C::func_2()
0000000000000000 V typeinfo for A
0000000000000000 V typeinfo for B
0000000000000000 V typeinfo for C
0000000000000000 V typeinfo name for A
0000000000000000 V typeinfo name for B
0000000000000000 V typeinfo name for C
0000000000000000 V vtable for C
                 U vtable for __cxxabiv1::__class_type_info
                 U vtable for __cxxabiv1::__vmi_class_type_info
    void C::func_1() { puts("func_1"); }
    void C::func_2() { puts("func_2"); }

By above steps you can find the content it points to. 通过上述步骤,您可以找到它指向的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM