In C ++ virtual functions can be inline function?

  • 1. The need to pay attention to a few points :
    • Virtual function can be inline, inline virtual functions can be modified, but when virtual functions can not be polymorphic inline.
    • Inline is a compiler compiler to inline the recommendation, and polymorphism virtual functions at runtime, the compiler can not know which code to run on the call, so the performance when virtual function polymorphism (runtime) can not be inline.
    • The only time inline virtual inline is: the compiler knows which object is called class (such as Base :: who ()), this will occur only with a pointer or reference to the actual object rather than the object of the compiler.
  • 2. The code examples are as follows:
        #include <iostream>
        using namespace std;
        // 基类
        class Base{
            public:
                inline virtual void who(){
                    cout << "I am Base\n";
                }
                virtual ~Base(){}
        };
        // 派生类
        class Derived:public Base{
            public:
                inline void who(){   // 不写inline时隐式内联
                    cout << "I am Derived\n";
                }
        };
    int  main(){
        // 此处的虚函数 who(),是通过类(Base)的具体对象(b)来调用的,编译期间就能确定了,所以它可以是内联的,但最终是否内联取决于编译器。
        Base b;
        b.who();
        // 此处的虚函数是通过指针调用的,呈现多态性,需要在运行时期间才能确定,所以不能为内联。
        Base *bptr = new Derived();
        bptr->who();
        // 因为Base有虚析构函数(virtual ~Base() {}),所以 delete 时,会先调用派生类(Derived)析构函数,再调用基类(Base)析构函数,防止内存泄漏。
        delete bptr;
        bptr = nullptr;
        return 0;
        
      }
    

Reproduced in: https: //www.jianshu.com/p/84a8335444dd

Guess you like

Origin blog.csdn.net/weixin_34319999/article/details/91194864