假设我有这堂课
class Point
{
inline float x() const { return v[0]; }
inline float y() const { return v[1]; }
inline float z() const { return v[2]; }
float v[3];
};
我愿意:
Point myPoint;
myPoint[0] = 5;
// unrelated code goes here
float myVal = myPoint.x() + 5;
-O2
或-O3
上的GCC将仅获得x()
来优化对v[0]
的所有调用吗? IE:
float myVal = myPoint.v[0] + 5;
或者有没有理由为什么这不可能?
更新:应该提一下,我的确意识到inline
对编译器的建议比其他任何建议都重要,但无论如何都在想。
还有一个问题,对此类进行模板化会对可以完成的优化有影响吗?
您可以在这里观察到差异:https://godbolt.org/
假设您有此代码(您无法编译:缺少;
,并且Point
没有[]
):
struct Point
{
inline float x() const { return v[0]; }
inline float y() const { return v[1]; }
inline float z() const { return v[2]; }
float v[3];
};
int main() {
Point myPoint;
myPoint.v[0] = 5;
float myVal = myPoint.x() + 5;
return myVal;
}
Point::x() const:
push rbp
mov rbp, rsp
mov QWORD PTR [rbp-8], rdi
mov rax, QWORD PTR [rbp-8]
movss xmm0, DWORD PTR [rax]
pop rbp
ret
main:
push rbp
mov rbp, rsp
sub rsp, 16
movss xmm0, DWORD PTR .LC0[rip]
movss DWORD PTR [rbp-16], xmm0
lea rax, [rbp-16]
mov rdi, rax
call Point::x() const
movss xmm1, DWORD PTR .LC0[rip]
addss xmm0, xmm1
movss DWORD PTR [rbp-4], xmm0
movss xmm0, DWORD PTR [rbp-4]
cvttss2si eax, xmm0
leave
ret
.LC0:
.long 1084227584
我不擅长阅读汇编程序,但我将以上内容与the output with -O3
进行比较就足以令人信服:
-O3
它可能是内联的,也可能不是。那里没有保证。但是,如果希望始终将其内联,请使用main:
mov eax, 10
ret
属性。参见文档[[gnu::always_inline]]