当我收到一个代码审查评论说虚函数不需要内联时,我得到了这个问题。
我认为内联虚函数可以在直接在对象上调用函数的场景中派上用场。但我想到的反驳是——为什么要定义虚拟然后使用对象来调用方法?
最好不要使用内联虚函数,因为它们几乎从不扩展?
我用于分析的代码片段:
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/