当前位置:网站首页>Ask and answer: dispel your doubts about the virtual function mechanism
Ask and answer: dispel your doubts about the virtual function mechanism
2022-07-03 20:51:00 【Your dream is like smoke, Brian】
List of articles
- Q1: Virtual functions (virtual function) How is it realized ?
- Q2: What is a pure virtual function (pure virtual function)?
- Q3: Does pure virtual function occupy virtual function table ?
- Q4: Can a constructor be a virtual function or a pure virtual function ?
- Q5: Can virtual functions be called in constructors ?
- Q6: Why does the destructor of the base class need to be declared as a virtual function ?
- Q7: Virtual functions can be declared inline (inline) Function? ?
- Q8: Multiple inheritance (virtual inheritance) What is the change of the virtual function table under ?
- Q9: Virtual functions can be overloaded (overload) Do you ?
- Q10: What is the extra cost of using virtual function mechanism ?
Q1: Virtual functions (virtual function) How is it realized ?
Virtual function mechanism , Through the virtual function table (vtable) Realization . Only when a virtual function is declared in a class , The compiler will add a virtual function table for this class . The virtual function table holds the addresses of all virtual functions of the class . The object of the class that declares the virtual function will hold a pointer to the base address of the virtual function table .
How to maintain virtual function table ? There are mainly three situations :
- Derived class override (override) Virtual function of base class
The corresponding virtual function pointer in the base class is changed to the pointer of the virtual function of the derived class . - The derived class inherits the virtual function of the base class
The pointer of the virtual function corresponding to the derived class is set to the pointer of the virtual function corresponding to the base class - Derived classes implement new virtual functions ( That is, it has a different function signature from all virtual functions in the base class ( Pay attention to distinguish overloads
overloadAnd rewriteoverrideThe concept of ).
Add , The pointer of the virtual function it implements .
Reference resources :
How are C++ objects laid out in memory? —— Bjarne Stroustrup’s C++ Style and Technique FAQ
Q2: What is a pure virtual function (pure virtual function)?
Concept :
- The declaration of a class function is followed by ”=0“, It is a pure virtual function .
- Pure virtual functions implicitly declare classes as abstract classes (abstract class)
- A class with at least one pure virtual function is called a pure virtual class . A class with only pure virtual functions is called C++ The interface (interface)
characteristic :
- Pure virtual classes cannot be instantiated .
- You must implement pure virtual functions in inherited pure virtual classes , Otherwise, the derived class is still a pure virtual class .
purpose :
- Occupy the pit : Make an appointment for “ Interface ” Delay the binding of the actual implementation to the run stage instead of the compilation stage .
See :
What is a pure virtual function? —— Bjarne Stroustrup’s C++ Style and Technique FAQ
Q3: Does pure virtual function occupy virtual function table ?
Pure virtual functions do occupy slots in their virtual function tables (slot) , But what is in the slot depends on the implementation of the compiler . generally speaking , The pointer in the slot is either assigned NULL, Or take the address of the specific function generated by the compiler . Performing behavior similar to assertions in these functions causes the compiler to issue an error prompt .
reflection : Pure virtual functions have virtual function tables . Here is an interesting discussion . A pure virtual function even if it declares a virtual function , But pure virtual functions cannot be instantiated , So what's the significance of pure virtual classes having their own virtual function table ? Perhaps the virtual function table also includes support RTTI Required information .
See in detail :How are virtual functions and vtable implemented?
Q4: Can a constructor be a virtual function or a pure virtual function ?
no way .
Virtual invocation is a mechanism that allows you to complete the work while providing some information . Special , fictitious (virtual) It allows us to call functions when we only know the interface and do not know the exact type of object .
Creating an object requires complete information . Special , To create objects , We must know the exact type of the object .
Combine the characteristics of the two mechanisms , We know that the constructor cannot be a virtual function or a pure virtual function .
See : Why don’t we have virtual constructors?
Q5: Can virtual functions be called in constructors ?
Although you can call , But this is undefined behavior . You should not expect the program to run in the state you expect .
When calling a virtual function in a constructor , The object is in a state that is not fully constructed . Therefore, calling virtual functions in constructors does not perform runtime binding as expected , Instead, the corresponding virtual function of the class to which the constructor belongs will be called .
See : Can I call a virtual function from a constructor?
Q6: Why does the destructor of the base class need to be declared as a virtual function ?
Only when the base class has at least one virtual function , We should declare the destructor of the base class as a virtual function .
When the base class has virtual functions , It means that the behavior of the base class is designed as the interface of the derived class . under these circumstances , We usually assign the base class pointer to the object address of the derived class , Use delete keyword . If the destructor of the base class is not declared as virtual, Will cause the destructor of the derived class not to be called , This leads to memory leaks .
See : Why are destructors not virtual by default?
Q7: Virtual functions can be declared inline (inline) Function? ?
Can be declared as an inline function . generally speaking , Even ordinary functions are declared inline , The compiler may still ignore inline identification .
There are additional requirements for inlining virtual functions . Only when virtual function calls do not produce dynamic parsing behavior , Will be expanded inline by the compiler . therefore , Only the compiler knows the exact object type of the virtual function being called , Virtual functions will be expanded inline .
This will only happen in
- Use the scope to avoid virtual function mechanism back and forth .
- Call virtual functions with actual objects instead of pointers and references to objects .
Reference resources :Are “inline virtual” member functions ever actually “inlined”?
Q8: Multiple inheritance (virtual inheritance) What is the change of the virtual function table under ?
Multiple inheritance Under the vtable Memory layout . The most common implementation is through multiple vtable Realization
verification :
The following derived classes D The instance size of is 64 Bit system 16 Bytes . So guess D Examples and DD Instances of both hold two vptr.
class B1{
virtual void funcB1(){
}
};
class B2{
virtual void funcB2(){
}
};
class D: public B1, B2{
};
class DD : public D{
};
D objD;
DD objDD;
sizeof(D) // 16 Bytes
sizeof(DD) // 16 Bytes
Add a test , Add one more B3 class , By D Inherit . Things have changed , Prove that our guess is correct . Test link
sizeof(D) // 24 Bytes
sizeof(DD) // 24 Bytes
all the minor details :
reflection : What about the layout under virtual inheritance ? How does virtual inheritance ensure that there is only one instance ?( Virtual inheritance (Virtual inheritance), Generally used to solve diamond inheritance The problem of .)
Q9: Virtual functions can be overloaded (overload) Do you ?
Sure .
for example :
class Base
{
public:
virtual void fun ( int x = 0)
{
cout << "Base::fun(), x = " << x << endl;
}
};
class Derived : public Base
{
public:
// error: 'virtual void Derived::fun(float)' marked 'override', but does not override
virtual void fun ( float x = 10.0 ) override
{
cout << "Derived::fun(), x = " << x << endl;
}
};
Getting rid of override After the logo , Compilation can pass . Derived classes here Derived Of fun Functions are considered overloaded .
quote : Overloading of virtual functions
Q10: What is the extra cost of using virtual function mechanism ?
Time cost : The call cost is not different from that of ordinary functions , Compared with ordinary functions, it costs more to find functions in the virtual function table , But this kind of expense has little effect , The real extra cost is that the virtual function table may affect the compiler optimization .
Space overhead : Each class that declares virtual functions holds its own virtual function table . therefore , When the level of inheritance is deeper , The more memory overhead .
In addition : Use RTTI It is more expensive than the virtual function mechanism :
dynamic_cast In some cases, you need to recursively traverse the entire class inheritance hierarchy .
all the minor details :
reflection : C++ in RTTI How the mechanism works
Reference resources :
边栏推荐
- Xai+ network security? Brandon University and others' latest "interpretable artificial intelligence in network security applications" overview, 33 page PDF describes its current situation, challenges,
- 同花顺开户注册安全靠谱吗?有没有风险的?
- Hcie security Day12: supplement the concept of packet filtering and security policy
- Use of CMD command
- Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
- Instructions for common methods of regular expressions
- Shortest path problem of graph theory (acwing template)
- Strange way of expressing integers (expanding Chinese remainder theorem)
- JVM JNI and PVM pybind11 mass data transmission and optimization
- Pytorch sets the weight and bias of the model to zero
猜你喜欢

How can the outside world get values when using nodejs to link MySQL

Reinforcement learning - learning notes 1 | basic concepts

The 29th day of force deduction (DP topic)

2.5 conversion of different data types (2)

XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向

《ActBERT》百度&悉尼科技大学提出ActBERT,学习全局局部视频文本表示,在五个视频-文本任务中有效!...

Qt6 QML Book/Qt Quick 3D/基础知识

Install and use Chrony, and then build your own time server

强基计划 数学相关书籍 推荐

"Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks
随机推荐
How can the outside world get values when using nodejs to link MySQL
Link aggregation based on team mechanism
AI enhanced safety monitoring project [with detailed code]
[gd32l233c-start] 5. FLASH read / write - use internal flash to store data
In 2021, the global revenue of thick film resistors was about $1537.3 million, and it is expected to reach $2118.7 million in 2028
浅析 Ref-NeRF
Discussion Net legacy application transformation
Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress
Qtablewidget control of QT
In 2021, the global general crop protection revenue was about $52750 million, and it is expected to reach $64730 million in 2028
淺析 Ref-NeRF
Thread, thread stack, method stack, the difference of creating thread
[Yugong series] go teaching course 002 go language environment installation in July 2022
阻塞非阻塞和同步异步的区分 参考一些书籍
强化學習-學習筆記1 | 基礎概念
Design e-commerce seckill system
如临现场的视觉感染力,NBA决赛直播还能这样看?
Etcd 基于Raft的一致性保证
电子科技大学|强化学习中有效利用的聚类经验回放