Home > Article > Backend Development > Do Virtual Functions Always Add the Size of a Pointer to an Object?
Alternative Virtual Function Call Implementations
In C , dynamic binding is facilitated through the virtual mechanism. While the standard specifies the expected behaviors of virtual function calls, the specific implementation varies across compilers. The virtual table and virtual pointer mechanism is widely employed by compilers such as G and Microsoft Visual Studio.
Alternative Implementations
Despite the prevalence of the virtual table approach, other implementations of dynamic dispatch for virtual functions do exist. One known alternative involves the use of an in-object pointer instead of a virtual pointer. This strategy allows for more efficient handling of complex objects with multiple bases and arrays, as only a single entry in a mapping table is required for all objects in an array.
Object Size and Virtual Functions
The statement that the size of a class with a virtual function will always be equal to the size of a pointer (the virtual pointer) is not universally true. The actual implementation of virtual function dispatch can influence the object's size. For instance, in the alternative implementation mentioned above, the size of an object with a virtual function may exceed the size of a pointer due to the additional storage required for the in-object pointer.
Limitations of Virtual Tables
While virtual tables are a common solution for dynamic dispatch, they also have limitations. For example, their use can result in large vtables and slow object initialization, particularly for complex mixin objects with multiple bases. This consequence stems from the requirement that the run-time type of a subobject must always be correct, even during construction.
Alternative Data Structures
One approach to overcome these limitations is to employ alternative data structures for storing meta-data. For instance, Judy arrays have been used to create a highly efficient mapping between object addresses and their corresponding meta-data. This approach provides fast lookup and modest storage requirements.
The above is the detailed content of Do Virtual Functions Always Add the Size of a Pointer to an Object?. For more information, please follow other related articles on the PHP Chinese website!