Pointers to virtual member functions. How does it work?

前端 未结 3 871
無奈伤痛
無奈伤痛 2020-12-03 07:12

Consider the following C++ code:

class A
{
public:
      virtual void f()=0;
};


int main()
{
     void (A::*f)()=&A::f;
}

If I\'d hav

3条回答
  •  有刺的猬
    2020-12-03 07:32

    It works because the Standard says that's how it should happen. I did some tests with GCC, and it turns out for virtual functions, GCC stores the virtual table offset of the function in question, in bytes.

    struct A { virtual void f() { } virtual void g() { } }; 
    int main() { 
      union insp { 
        void (A::*pf)();
        ptrdiff_t pd[2]; 
      }; 
      insp p[] = { { &A::f }, { &A::g } }; 
      std::cout << p[0].pd[0] << " "
                << p[1].pd[0] << std::endl;
    }
    

    That program outputs 1 5 - the byte offsets of the virtual table entries of those two functions. It follows the Itanium C++ ABI, which specifies that.

提交回复
热议问题