Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The rule violated here is documented in C++03 3.10/15 [basic.lval], which specifies what is referred to informally as the "strict aliasing rule"</p> <blockquote> <p>If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:</p> <ul> <li><p>the dynamic type of the object,</p></li> <li><p>a cv-qualified version of the dynamic type of the object,</p></li> <li><p>a type that is the signed or unsigned type corresponding to the dynamic type of the object,</p></li> <li><p>a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,</p></li> <li><p>an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union),</p></li> <li><p>a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,</p></li> <li><p>a char or unsigned char type.</p></li> </ul> </blockquote> <p>In short, given an object, you are only allowed to access that object via an expression that has one of the types in the list. For a class-type object that has no base classes, like <code>std::vector&lt;T&gt;</code>, basically you are limited to the types named in the first, second, and last bullets.</p> <p><code>std::vector&lt;Base*&gt;</code> and <code>std::vector&lt;Derived*&gt;</code> are entirely unrelated types and you can't use an object of type <code>std::vector&lt;Base*&gt;</code> as if it were a <code>std::vector&lt;Derived*&gt;</code>. The compiler could do all sorts of things if you violate this rule, including:</p> <ul> <li><p>perform different optimizations on one than on the other, or </p></li> <li><p>lay out the internal members of one differently, or </p></li> <li><p>perform optimizations assuming that a <code>std::vector&lt;Base*&gt;*</code> can never refer to the same object as a <code>std::vector&lt;Derived*&gt;*</code></p></li> <li><p>use runtime checks to ensure that you aren't violating the strict aliasing rule</p></li> </ul> <p>[It might also do none of these things and it might "work," but there's no guarantee that it will "work" and if you change compilers or compiler versions or compilation settings, it might all stop "working." I use the scare-quotes for a reason here. :-)]</p> <p>Even if you just had a <code>Base*[N]</code> you could not use that array as if it were a <code>Derived*[N]</code> (though in that case, the use would probably be safer, where "safer" means "still undefined but less likely to get you into trouble).</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