c++: Does a vtable contains pointers to non-virtual functions?

后端 未结 4 1686
Happy的楠姐
Happy的楠姐 2021-02-09 03:28

vtable contains pointers to virtual functions of that class. Does it also contains pointers to non-virtual functions as well?

Thx!

相关标签:
4条回答
  • 2021-02-09 04:14

    Whether or not a "vtable" is used by any implementation isn't defined by the standard. Most implementations use a table of function pointers although the functions pointed to are typically not directly those being called (instead, the pointed to function may adjust the pointer before calling the actual function).

    Whether or not non-virtual functions show up in this table is also not defined by standard. After all, the standard doesn't even require the existence of a vtable. Normally, non-virtual function are not in a virtual function table since any necessary pointer adjustments and call can be resolved at compile- or link-time. I could imagine an implementation treating all functions similarly and, thus, using a pointer in the virtual function table in all cases. I wouldn't necessary be very popular. However, it might be a good way to implement C++ in an environment where it seamlessly interacts with a more flexible object system, e.g., languages where individual functions can be replaced at run-time (my understanding is that something like this is possible, e.g., in python).

    0 讨论(0)
  • 2021-02-09 04:14

    No. A vtable only contains pointers to virtual functions in the same class or file.

    0 讨论(0)
  • 2021-02-09 04:24

    It's an implementation detail, but no. If an implementation put pointers to non-virtual functions into a vtable it couldn't use these pointers for making function calls because it would often cause incorrect non-virtual functions to be called.

    When a non-virtual function is called the implementation must use the static type of the object on which the function is being called to determine the correct function to call. A function stored in a vtable accessed by a vptr will be dependent on the dynamic type of the object, not any static type of a reference or pointer through which it is being accessed.

    0 讨论(0)
  • 2021-02-09 04:26

    No, it doesn't.

    As calls to non-virtual methods can be resolved during compilation (since compiler knows the addresses of non virtual functions), the compiler generates instructions to call them 'directly' (i.e. statically).

    There is no reason to go through vtable indirection mechanism for methods which are known during compiling.

    0 讨论(0)
提交回复
热议问题