问题描述
假设我有以下代码
void f(PolymorphicType *p)
{
for (int i = 0; i < 1000; ++i)
{
p->virtualMethod(something);
}
}
编译器生成的代码解除引用 p
' vtable
条目 virtualMethod
1或1000次?我使用的是Microsoft的编译器。
Will the compiler's generated code dereference p
's vtable
entry for virtualMethod
1 or 1000 times? I am using Microsoft's compiler.
编辑
现实世界的案例我在看。 line-> addPoint()
是虚拟的关注方法。我没有装配经验,所以我要慢慢来...
here is the generated assembly for the real-world case I'm looking at. line->addPoint()
is the virtual method of concern. I have no assembly experience, so I'm going over it slowly...
; 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 : }
推荐答案
一般来说,可能。该函数可以破坏 * this
和placement-new派生自该空间中相同基础的其他对象。
In general, no, it is not possible. The function could destroy *this
and placement-new some other object derived from the same base in that space.
编辑:更容易,该函数只需更改 p
。编译器不可能知道谁具有 p
的地址,除非它是所涉及的优化单元的本地。
even easier, the function could just change p
. The compiler cannot possibly know who has the address of p
, unless it is local to the optimization unit in question.
这篇关于C ++编译器可以在同一个指针上优化重复的虚函数调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!