C++ FAQ

目录

1 DONE Virtual函数是否不会被Inlined?

  • 当编译器准确地知道对象的准确类时,虚函数可能会被内联。这要求编译器有一个实际的 对象而不是对象指针,例如一个本地对象,或者一个全局的,或静态的对象。
  • Refer: http://www.cs.technion.ac.il/users/yechiel/c++-faq/inline-virtuals.html
  • Test Code 适用-O1编译,某机器运行结果为400、2500、2200,确实有inline差异
#include <iostream>
#include <sys/time.h>

using namespace std;

class Base
{
public:
    Base() : mDummy(0) {}
    virtual ~Base() {}
    virtual void Func(int i) = 0;
    void PrintDummy()
    {
        cout<<"Dummy="<<mDummy<<endl;
    }
protected:
    int mDummy;
};

class Derived : public Base
{
public:
    virtual void Func(int i)
    {
        mDummy += i;
    }
};

static inline long getus()
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    return tp.tv_sec * 1000 * 1000 + tp.tv_usec;
}

#define LOOP_LIMITS     (1000*1000*10)

static void fpobj(Derived *pobj)
{
    long ms1, ms2;
    ms1 = getus();
    for (int i = 0; i < 1000000; ++i)
        pobj->Func(i);
    ms2 = getus();
    cout<<"Time3: "<<ms2 - ms1<<endl;
}

int main()
{
    long ms1, ms2;
    Derived obj, *pobj;

    pobj = &obj;

    ms1 = getus();
    for (int i = 0; i < 1000000; ++i)
        obj.Func(i);
    ms2 = getus();
    cout<<"Time1: "<<ms2 - ms1<<endl;

    ms1 = getus();
    for (int i = 0; i < 1000000; ++i)
        pobj->Func(i);
    ms2 = getus();
    cout<<"Time2: "<<ms2 - ms1<<endl;

    fpobj(pobj);
    obj.PrintDummy();

    return 0;
}

2 Reference