简体   繁体   中英

c++ Virtual Function performance for x calls on the same object

If i have a to call x virtual function on the same object, will the compiler be smart enough to somehow remember the vtable address or it will dig the address on each x call? Cheers

Whenever there is a virtual function inside definition of a class either through inheritance or normal declaration a vtable is created.

Vtables themselves are generally stored in the static data segment as they are class specific as compared to object specific.Generally whenever an object of a class is created vtable pointer pointing to the vtable of the class is generally stored in the beginning of the object's memory location but it depends on the compiler in the end how it implements the virtual function.

Now as long as the object remains in the memory, It includes pointer to its Vtable.So if you call the virtual function on the same object ,just the pointer to vtable is referenced to get vtable location.No digging of address is required.

There are several good answers to a similar question here: Cost of a virtual function in a tight loop

In general, to understand the C++ object model and the implementation choices Stroustrup made, I recommend his book "The design and evolution of the C++ language".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM