【发布时间】:2011-09-03 06:41:32
【问题描述】:
如果类的类型在编译时已知(例如,如果类实例没有通过引用或指针使用,如中所示),我希望编译器能够静态解析对虚函数的函数调用案例 1) 下面)。
但是,我观察到 Visual Studio 2010 的 C++ 编译器有一个奇怪的行为,我想知道编译器是否有任何理由在类的实例时不将调用静态绑定到“正确的”虚函数带有虚函数的是结构中的成员,通过引用访问。
我是否应该期望编译器在下面的案例 2) 中静态绑定对 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
}
【问题讨论】:
-
有趣的是,Clang 似乎也没有优化虚拟调用。有趣。 (如果我将
B::f标记为final,它将成功优化cr.b.f())
标签: c++ performance visual-studio-2010 compiler-construction polymorphism