当且仅当函数通过静态绑定调用时,G++ 4.8.1似乎尊重虚拟成员函数的pure
和函数属性。const
给定以下源代码:
struct Base {
void w();
void x() __attribute__ ((const));
virtual void y();
virtual void z() __attribute__ ((const));
};
struct Derived : public Base {
void w() __attribute__ ((const));
void x();
virtual void y() __attribute__ ((const));
virtual void z();
};
void example() {
Base b, *pb;
Derived d, *pd;
b.w(); // called
b.x(); // not called
b.y(); // called
b.z(); // not called
pb->w(); // called
pb->x(); // not called
pb->y(); // called
pb->z(); // called
d.w(); // not called
d.x(); // called
d.y(); // not called
d.z(); // called
pd->w(); // not called
pd->x(); // called
pd->y(); // called
pd->z(); // called
}
…编译器生成以下(摘录)汇编代码:
void example() {
Base b, *pb;
Derived d, *pd;
b.w(); // called
1c: e8 00 00 00 00 callq 21 <_Z7examplev+0x21>
b.x(); // not called
b.y(); // called
21: 48 89 e7 mov %rsp,%rdi
24: e8 00 00 00 00 callq 29 <_Z7examplev+0x29>
b.z(); // not called
pb->w(); // called
29: 48 89 df mov %rbx,%rdi
2c: e8 00 00 00 00 callq 31 <_Z7examplev+0x31>
pb->x(); // not called
pb->y(); // called
31: 48 8b 2b mov (%rbx),%rbp
34: 48 89 df mov %rbx,%rdi
37: ff 55 00 callq *0x0(%rbp)
pb->z(); // called
3a: 48 89 df mov %rbx,%rdi
3d: ff 55 08 callq *0x8(%rbp)
d.w(); // not called
d.x(); // called
40: 48 8d 7c 24 10 lea 0x10(%rsp),%rdi
45: e8 00 00 00 00 callq 4a <_Z7examplev+0x4a>
d.y(); // not called
d.z(); // called
4a: 48 8d 7c 24 10 lea 0x10(%rsp),%rdi
4f: e8 00 00 00 00 callq 54 <_Z7examplev+0x54>
pd->w(); // not called
pd->x(); // called
54: 48 89 df mov %rbx,%rdi
57: e8 00 00 00 00 callq 5c <_Z7examplev+0x5c>
pd->y(); // called
5c: 48 8b 2b mov (%rbx),%rbp
5f: 48 89 df mov %rbx,%rdi
62: ff 55 00 callq *0x0(%rbp)
pd->z(); // called
65: 48 89 df mov %rbx,%rdi
68: ff 55 08 callq *0x8(%rbp)
}