Note that there are some explanatory texts on larger screens.

plurals
  1. POLTO, Devirtualization, and Virtual Tables
    primarykey
    data
    text
    <p>Comparing virtual functions in C++ and virtual tables in C, do compilers in general (and for sufficiently large projects) do as good a job at devirtualization?</p> <p>Naively, it seems like virtual functions in C++ have slightly more semantics, thus may be easier to devirtualize.</p> <p><em>Update:</em> Mooing Duck mentioned inlining devirtualized functions. A quick check shows missed optimizations with virtual tables:</p> <pre><code>struct vtab { int (*f)(); }; struct obj { struct vtab *vtab; int data; }; int f() { return 5; } int main() { struct vtab vtab = {f}; struct obj obj = {&amp;vtab, 10}; printf("%d\n", obj.vtab-&gt;f()); } </code></pre> <p>My GCC will not inline f, although it is called directly, i.e., devirtualized. The equivalent in C++,</p> <pre><code>class A { public: virtual int f() = 0; }; class B { public: int f() {return 5;} }; int main() { B b; printf("%d\n", b.f()); } </code></pre> <p>does even inline f. So there's a first difference between C and C++, although I don't think that the added semantics in the C++ version are relevant in this case.</p> <p><em>Update 2:</em> In order to devirtualize in <em>C</em>, the compiler has to prove that the function pointer in the virtual table has a certain value. In order to devirtualize in <em>C++</em>, the compiler has to prove that the object is an instance of a particular class. It would seem that the proof is harder in the first case. However, virtual tables are typically modified in only very few places, and most importantly: just because it looks harder, doesn't mean that compilers aren't as good in it (for otherwise you might argue that xoring is generally faster than adding two integers).</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload