16

假设我有以下代码

void f(PolymorphicType *p)
{
    for (int i = 0; i < 1000; ++i)
    {
        p->virtualMethod(something);
    }
}

编译器生成的代码会取消引用1 或 1000 次pvtable条目吗?virtualMethod我正在使用微软的编译器。

编辑

这是为我正在查看的真实案例生成的程序集。 line->addPoint()是关注的虚方法。我没有组装经验,所以我慢慢复习...

; 369  :        for (int i = 0; i < numPts; ++i)

    test    ebx, ebx
    je  SHORT $LN1@RDS_SCANNE
    lea edi, DWORD PTR [ecx+32]
    npad    2
$LL3@RDS_SCANNE:

; 370  :        {
; 371  :            double *pts = pPoints[i].SystemXYZ;
; 372  :            line->addPoint(pts[0], pts[1], pts[2]);

    fld QWORD PTR [edi+8]
    mov eax, DWORD PTR [esi]
    mov edx, DWORD PTR [eax+16]
    sub esp, 24                 ; 00000018H
    fstp    QWORD PTR [esp+16]
    mov ecx, esi
    fld QWORD PTR [edi]
    fstp    QWORD PTR [esp+8]
    fld QWORD PTR [edi-8]
    fstp    QWORD PTR [esp]
    call    edx
    add edi, 96                 ; 00000060H
    dec ebx
    jne SHORT $LL3@RDS_SCANNE
$LN314@RDS_SCANNE:

; 365  :        }
4

2 回答 2

6

一般来说,不,这是不可能的。该函数可以销毁*this并放置新的从该空间中的同一基础派生的其他一些对象。

编辑:更简单,功能可以改变p. 编译器不可能知道谁拥有 的地址p,除非它是相关优化单元的本地地址。

于 2013-02-07T17:50:12.080 回答
2

一般来说不可能,但有一些特殊情况可以优化,尤其是在程序间分析中。VS2012全优化和全程序优化编译这个程序:

#include <iostream>

using namespace std;

namespace {
struct A {
  virtual void foo() { cout << "A::foo\n"; }
};

struct B : public A {
  virtual void foo() { cout << "B::foo\n"; }
};

void test(A& a) {
  for (int i = 0; i < 100; ++i)
    a.foo();
}
}

int main() {
  B b;
  test(b);
}

至:

01251221  mov         esi,64h  
01251226  jmp         main+10h (01251230h)  
01251228  lea         esp,[esp]  
0125122F  nop  
01251230  mov         ecx,dword ptr ds:[1253044h]  
01251236  mov         edx,12531ACh  
0125123B  call        std::operator<<<std::char_traits<char> > (012516B0h)  
01251240  dec         esi  
01251241  jne         main+10h (01251230h)  

所以它有效地优化了循环:

for(int i = 0; i < 100; ++i)
  cout << "B::foo()\n";
于 2013-02-07T19:04:21.097 回答