假设我有以下代码
void f(PolymorphicType *p)
{
for (int i = 0; i < 1000; ++i)
{
p->virtualMethod(something);
}
}
编译器生成的代码会对p
的vtable
条目进行1次还是1000次的解引用以调用virtualMethod
?我正在使用Microsoft的编译器。
编辑
这是我关注的真实案例的汇编生成代码。 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 : }
mov edx, DWORD PTR [eax+16]
...call edx
。我猜它每次都在查看虚函数表。 - japreiss