内联虚拟函数真的是无意义的吗? [英] Are inline virtual functions really a non-sense?

查看:152
本文介绍了内联虚拟函数真的是无意义的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到这个问题,当我收到一个代码审查意见,说虚拟功能不需要内联。

I got this question when I received a code review comment saying virtual functions need not be inline.

我认为内联虚拟函数可以派上用场直接调用对象的函数。但是我的反对意见是 - 为什么要定义虚拟然后使用对象来调用方法?

I thought inline virtual functions could come in handy in scenarios where functions are called on objects directly. But the counter-argument came to my mind is -- why would one want to define virtual and then use objects to call methods?

最好不要使用内联虚拟

我用于分析的代码段:

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 ++常见问题


内联虚拟调用
只能被内联是编译器
知道对象的确切类
这是虚拟
函数调用的目标,当编译器有一个实际的对象
而不是一个指针或引用
时,只能发生
。也就是说,在本地
对象,全局/静态对象或
完全包含的对象在
组合内。

"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."

这篇关于内联虚拟函数真的是无意义的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆