c++ - 内联虚函数真的是无稽之谈吗?

标签 c++ inline virtual-functions

当我收到一个代码审查评论说虚函数不需要内联时,我得到了这个问题。

我认为内联虚函数可以在直接在对象上调用函数的场景中派上用场。但我想到的反驳是——为什么要定义虚拟然后使用对象来调用方法?

最好不要使用内联虚函数,因为它们几乎从不扩展?

我用于分析的代码片段:

class Temp
{
public:

    virtual ~Temp()
    {
    }
    virtual void myVirtualFunction() const
    {
        cout<<"Temp::myVirtualFunction"<<endl;
    }

};

class TempDerived : public Temp
{
public:

    void myVirtualFunction() const
    {
        cout<<"TempDerived::myVirtualFunction"<<endl;
    }

};

int main(void) 
{
    TempDerived aDerivedObj;
    //Compiler thinks it's safe to expand the virtual functions
    aDerivedObj.myVirtualFunction();

    //type of object Temp points to is always known;
    //does compiler still expand virtual functions?
    //I doubt compiler would be this much intelligent!
    Temp* pTemp = &aDerivedObj;
    pTemp->myVirtualFunction();

    return 0;
}

最佳答案

有时可以内联虚拟函数。优秀 C++ faq 的摘录:

"The only time an inline virtual call can be inlined is when the compiler knows the "exact class" of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/static object, or a fully contained object inside a composite."

关于c++ - 内联虚函数真的是无稽之谈吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/733737/

相关文章:

html - 在线显示图片

c++ - 为什么这段代码是 "not ambigious!"——虚函数

c++ - 模板和循环依赖

c++ - 是否存在与平台无关的C++ fork 过程(例如某些标准库)?如何使我的代码可移植?

if-statement - Handlebars : native inline conditional expression or equivalent?

c++ - 内联模板函数

c++ - 数据类型 inst 转换正确吗?

C++:这种编译时多态性技术如何称呼?有什么优点和缺点?

C++ 类持有并返回指向另一个类的指针

C++ cout 十六进制格式