Note that there are some explanatory texts on larger screens.

plurals
  1. POHoisting the dynamic type out of a loop (a.k.a. doing Java the C++ way)
    text
    copied!<p>I was discussing the merits of "modern" languages compared to C++ with some friends recently, when the following came up (I think inspired by Java):</p> <p>Does any C++ compiler optimize dynamic dispatch out of a loop? If not, is there any kind of construction that would allow the author to force (or strongly encourage) such an optimization?</p> <p>Here's the example. Suppose I have a polymorphic hierarchy:</p> <pre><code>struct A { virtual int f() { return 0; } }; struct B : A { virtual int f() { return /* something complicated */; } /*...*/ }; </code></pre> <p>Now I have a loop that accumulates <code>f()</code>:</p> <pre><code>int acc(const A * p, unsigned int N) { int result = 0; for (unsigned int i = 0; i != N; ++i) result += p-&gt;f(); // #1 return result; } </code></pre> <p>In this function, the dynamic dispatch <code>p-&gt;f()</code> appears to happen during every round of the loop. However, the ultimate target of the dispatch blatantly (?) cannot vary.</p> <p>Question: Does this dynamic dispatch get optimized by the compiler? If not, is there any way to rewrite the code to force this optimization, or at least enable the compiler to recognize this? Is there any good test code that can tell me quickly whether this is getting optimized already?</p> <p>I'm interested in both language and implementation answers, such as "this is impossible according to the standard", or "yes, MSVC does this with option <code>/xyzzy</code>".</p> <p><sub>Some comparative remarks: Apparently Java does optimize and even <em>inline</em> the call in the inner loop if appropriate. Objective-C++ apparently allows you to query the dynamic function pointer and store it.</sub></p> <p><em>Clarification:</em> The main use case which I'm interested in is when the base class and the function with the loop (like the accumulator) are part of a separate translation unit or library, and there is no control over or knowledge of the derived classes.</p>
 

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