Virtuals are hard to optimize away.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class A | |
| { | |
| public: | |
| virtual void f() = 0; | |
| }; | |
| class B : public A | |
| { | |
| virtual void f() | |
| { | |
| // ... | |
| } | |
| }; | |
| void g(B* x) | |
| { | |
| // The compiler/linker CAN'T turn this into a non-virtual call unless it can | |
| // prove at compile time that x actually points to an instance of B. | |
| // | |
| // This is *really hard* in general. | |
| x->f(); | |
| } | |
| // Consider this: Suppose that B is the only class deriving from A in your entire | |
| // program. Then the compiler can assume that "x" is actually a B*, since that's | |
| // the only valid argument you could pass, correct? | |
| // | |
| // No, it actually can't! What happens if, somewhere in another DLL, there is this | |
| // code: | |
| class C : public B | |
| { | |
| virtual void f() | |
| { | |
| // ... | |
| } | |
| }; | |
| // The compiler doesn't know about this when the executable / DLL / shared library | |
| // containing B gets compiled. But it has to assume that some other piece of code | |
| // might know about B, and derive from it. Which in turn means that if there's *any* | |
| // code path leading to "g" inside the original program that might either be called | |
| // from the outside, or call into a DLL/shared library and get a "B*" back, it could | |
| // in fact return a pointer to a C, which would make the above optimization invalid. | |
| // | |
| // This is a ridiculously hard problem to solve, there's no margin for error (getting | |
| // this wrong would break most programs that have plug-in interface, for example), | |
| // it's for a relatively small gain, and hence I would be very surprised if any | |
| // C++ compiler was actually willing to try this. :) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment