r/cpp • • Mar 02 '26

Devirtualization and Static Polymorphism

https://david.alvarezrosa.com/posts/devirtualization-and-static-polymorphism/
57 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/SirClueless Mar 10 '26

a typical case in libraries

Not just libraries, and not just "typical case". To my knowledge GCC adds these guards when compiling every single application, even with aggressive LTO and -fwhole-program.

The reason is that a year from now someone can write a new subclass of BaseClass, compile it into a shared library, put it into your LD_PRELOAD, and the next time you call dlopen someone is calling into your application with new vtable pointers the compiler could never have known about without time travel.

There is actually a clang-only compiler flag, -fwhole-program-vtables, that allows the compiler to assume this won't happen to certain classes. But to my knowledge there is no way to replicate this behavior in GCC (if anyone knows different, please please let me know!).

1

u/matthieum Mar 10 '26

I believe GCC is smart enough to elide the fallback case if the class is defined in anonymous namespace, which prevents subclassing in a different TU.

Bit limited, admittedly.