c++ - 编译器何时可以将调用静态绑定(bind)到虚函数?

标签 c++ performance visual-studio-2010 compiler-construction polymorphism

如果类的类型在编译时已知(例如,如果类实例没有通过引用或指针使用,如中所示),我希望编译器能够静态解析对虚函数的函数调用案例 1) 下面)。

但是,我观察到 Visual Studio 2010 的 C++ 编译器有一个奇怪的行为,我想知道编译器是否有任何理由在类的实例时不将调用静态绑定(bind)到“正确的”虚函数带有虚函数的是结构中的成员,通过引用访问。

我是否应该期望编译器在下面的情况 2) 中静态绑定(bind)对 f() 的调用?即使 aA 而不是 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/

相关文章:

c++ - 为什么 std::queue 没有 operator[]?

c++ - std::array 类成员在编译时设置?

c++ - 我应该默认虚拟析构函数吗?

visual-studio-2010 - 附加到流程问题

visual-c++ - 编译 x64 代码时, "x86_amd64"和 "amd64"有什么区别?

c++ - GLFW 的 VC++ LNK 错误

c++ - 不同的智能指针可以引用同一个对象吗?

c# - 为什么本地数组的读/写速度比静态数组快?

MySQL选择没有子查询的最大值

mysql - 使用 ORDER BY 时 MySQL 查询速度慢