如果类的类型在编译时已知(例如,如果类实例没有通过引用或指针使用,如中所示),我希望编译器能够静态解析对虚函数的函数调用案例 1) 下面)。
但是,我观察到 Visual Studio 2010 的 C++ 编译器有一个奇怪的行为,我想知道编译器是否有任何理由在类的实例时不将调用静态绑定(bind)到“正确的”虚函数带有虚函数的是结构中的成员,通过引用访问。
我是否应该期望编译器在下面的情况 2) 中静态绑定(bind)对 f() 的调用?即使 a
是 A
而不是 A&
,cr 的“引用”是否会以某种方式传播到 cr.a?
struct A
{
virtual void f() ;
virtual ~A() ;
};
struct B : A
{
virtual void f() ;
virtual ~B() ;
};
struct C {
A a ;
B b ;
};
C & GetACRef() ;
void test()
{
// Case 1) The following calls to f() are statically bound i.e.
// f() is called without looking up the virtual function ptr.
C c ;
c.a.f() ;
c.b.f() ;
A a ;
a.f() ;
// Case 2) The following calls to f() go through the dynamic dispatching
// virtual function lookup code. You can check if you generate the .asm
// for this file.
C & cr = GetACRef() ; // Note that C is not polymorphic
cr.a.f() ; // visual C++ 2010 generates call to f using virtual dispatching
cr.b.f() ; // visual C++ 2010 generates call to f using virtual dispatching
}
最佳答案
显然编译器编写者并没有费心去解决这个问题。也许它在实际代码中并不常见,不值得他们关注。
如果 GetACRef
在别处定义,C 也有可能是多态的,这可能会影响优化。
请注意,编译器并不能解决所有可能的情况,即小型测试程序对人类来说是“显而易见的”。编译器的重点是大型实际程序中经常发生的情况。
关于c++ - 编译器何时可以将调用静态绑定(bind)到虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7291596/