As I understand, the location of the virtual
function pointer table in an object is compiler dependent.
Are there any pros/cons of placing this pointer at the beginning of the object vs at the end or vice-versa?
相关问题
- how to define constructor for Python's new Nam
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Keeping track of variable instances
- Why does const allow implicit conversion of refere
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
Yes it is completely implementation dependent.
For a simple inheritance hierarchy it is located at the beginning of the object but for a complex hierarchy it won't be.
Anyhow, any source code you write should not rely on where it is located, in fact any code you write should not rely on even existence of a virtual table or a virtual table pointer.
The C++ Standard does not mandate that virtual dispatch be implemented through virtual table and pointer, an implementation is free to implement it using an other implementation method, However all mainstream compilers do implement this through table pointer mechanism the important point to note is they may differ in exact implementation of where the pointer is located etc.
The mere existence of a virtual function table is compiler dependent (but all compilers do), and the location is not mandated either... In all compilers of which I know the details, the vptr is stored in the beginning of the object. The reason is that it provides a uniform location. Consider a class hierarchy:
If the vptr was stored at the end of the object, then it would be after
sizeof(T)
bytes for an object of complete typebase
. Now when you have an object of complete typederived
, the layout of thebase
sub object must be compatible with the layout of a completebase
object, so thevptr
would still have to besizeof(T)
bytes inside the object, which would be somewhere in the middle of thederived
object (sizeof(T)
from the beginning,sizeof(T1)
before the end). So it would no longer be at the end of the object.Additionally, given a
this
pointer, a virtual call requires an indirection through the vtable, which basically is dereferencing thevptr
, adding an offset and jumping to the memory location stored there. If thevptr
was stored at the end of the object, for each virtual call there would be an extra addition tothis
before dereferencing thevptr
.