我期望编译器能够静态解析对函数的函数调用,如果类的类型在编译时是已知的(例如,如果没有通过引用或指针使用类实例,如案例1中所示)下面).
但是,我观察到Visual Studio 2010的C++编译器有一种奇怪的行为,我想知道当虚拟类的实例时,编译器是否有任何理由不静态绑定对"正确"虚函数的调用函数是通过引用访问的结构中的成员.
我是否希望编译器在下面的案例2中静态绑定对f()的调用?cr的"参考"是否会以某种方式传播到cr.a,即使它a是一个A而不是一个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() ; …Run Code Online (Sandbox Code Playgroud) c++ compiler-construction polymorphism performance visual-studio-2010