Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Short answer: offsetof is a feature that is only in the C++ standard for legacy C compatibility. Therefore it is basically restricted to the stuff than can be done in C. C++ supports only what it must for C compatibility.</p> <p>As offsetof is basically a hack (implemented as macro) that relies on the simple memory-model supporting C, it would take a lot of freedom away from C++ compiler implementors how to organize class instance layout.</p> <p>The effect is that offsetof will often work (depending on source code and compiler used) in C++ even where not backed by the standard - except where it doesn't. So you should be very careful with offsetof usage in C++, especially since I do not know a single compiler that will generate a warning for non-POD use...</p> <p><b>Edit</b>: As you asked for example, the following might clarify the problem:</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct A { int a; }; struct B : public virtual A { int b; }; struct C : public virtual A { int c; }; struct D : public B, public C { int d; }; #define offset_d(i,f) (long(&amp;(i)-&gt;f) - long(i)) #define offset_s(t,f) offset_d((t*)1000, f) #define dyn(inst,field) {\ cout &lt;&lt; "Dynamic offset of " #field " in " #inst ": "; \ cout &lt;&lt; offset_d(&amp;i##inst, field) &lt;&lt; endl; } #define stat(type,field) {\ cout &lt;&lt; "Static offset of " #field " in " #type ": "; \ cout.flush(); \ cout &lt;&lt; offset_s(type, field) &lt;&lt; endl; } int main() { A iA; B iB; C iC; D iD; dyn(A, a); dyn(B, a); dyn(C, a); dyn(D, a); stat(A, a); stat(B, a); stat(C, a); stat(D, a); return 0; } </code></pre> <p>This will crash when trying to locate the field <code>a</code> inside type <code>B</code> statically, while it works when an instance is available. This is because of the virtual inheritance, where the location of the base class is stored into a lookup table.</p> <p>While this is a contrived example, an implementation could use a lookup table also to find the public, protected and private sections of a class instance. Or make the lookup completely dynamic (use a hash table for fields), etc.</p> <p>The standard just leaves all possibilities open by restricting offsetof to POD (IOW: no way to use a hash table for POD structs... :)</p> <p>Just another note: I had to reimplement offsetof (here: offset_s) for this example as GCC actually errors out when I call offsetof for a field of a virtual base class.</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