The following code does not get devirtualized by gcc. Any ideas what I can do to convince gcc to devirtualize?
struct B /* final */ {
virtual int foo() { return 3; }
};
struct C {
B& b;
__attribute__((noinline))
C( B& b ) : b(b) {
}
int foo() {
return b.foo();
}
};
int main() {
B b;
C c(b);
int res = c.foo();
return res;
}
I naively thought that this would be devirtualized ( at least speculatively ) and inlined.
In real life code where the constructor is another compilation unit the compiler will not be able to see the body of the constructor (hence the noinline attribute). It is also not final to mimic some real world requirements.
Devirtualization happens when compiler knows for the type of object in compile time. Here you have noinline for C::C making impossible for main to know what type of object actually end ups to C::b during construction.