What's the easiest way to print the address of a member function?

走远了吗. 提交于 2019-12-13 08:43:30

问题


If I have a base class with a pure-virtual function, and a derived class that implements that function - what's the easiest way I can print out the address that the function actually gets called at?

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

class B:A { 
    public: 
        void func() { /*implementation*/ }
        void func2() { *** I WANT TO PRINT THE ADDRESS OF func() HERE! *** }
};

Also, what's the easiest way to print out the address of a static function in a class, and to print out the address of a global function?


回答1:


[Edited] As far as I know, there's no way to get the address of the function that actually will be called, regardless of virtualness. For virtual methods specifically, the method and destination of virtual dispatch is left to the implementation. However even for normal functions the function pointer may not be the actual code address of the function (although I suspect there are cases where it is).




回答2:


c++ does not give any portable means of printing the address of a virtual function.




回答3:


The easiest way is to figure out the option to get your linker to output a link map, and look up the function name there.




回答4:


A method pointer is not always an address. It is in fact (on gcc) two things:

  • An offset
  • An address or an index

When the last bit of the member function pointer is 1 the second part is the offset in the vtable which indicate the method to call otherwise it is the address of the member function. The offset is added to the this pointer.

That's why a member function pointer is bigger than a common pointer. Also, you should notice that contrary to the function pointer, there is an overhead using member function pointer.



来源:https://stackoverflow.com/questions/7166254/whats-the-easiest-way-to-print-the-address-of-a-member-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!