Note that there are some explanatory texts on larger screens.

plurals
  1. POstrict aliasing and alignment
    primarykey
    data
    text
    <p>I need a safe way to alias between arbitrary POD types, conforming to ISO-C++11 explicitly considering 3.10/10 and 3.11 of n3242 or later. There are a lot of questions about strict aliasing here, most of them regarding C and not C++. I found a "solution" for C which uses unions, probably using this section</p> <blockquote> <p>union type that includes one of the aforementioned types among its elements or nonstatic data members</p> </blockquote> <p>From that I built this.</p> <pre><code>#include &lt;iostream&gt; template &lt;typename T, typename U&gt; T&amp; access_as(U* p) { union dummy_union { U dummy; T destination; }; dummy_union* u = (dummy_union*)p; return u-&gt;destination; } struct test { short s; int i; }; int main() { int buf[2]; static_assert(sizeof(buf) &gt;= sizeof(double), ""); static_assert(sizeof(buf) &gt;= sizeof(test), ""); access_as&lt;double&gt;(buf) = 42.1337; std::cout &lt;&lt; access_as&lt;double&gt;(buf) &lt;&lt; '\n'; access_as&lt;test&gt;(buf).s = 42; access_as&lt;test&gt;(buf).i = 1234; std::cout &lt;&lt; access_as&lt;test&gt;(buf).s &lt;&lt; '\n'; std::cout &lt;&lt; access_as&lt;test&gt;(buf).i &lt;&lt; '\n'; } </code></pre> <p>My question is, just to be sure, is this program legal according to the standard?<sup>*</sup></p> <p>It doesn't give any warnings whatsoever and works fine when compiling with MinGW/GCC 4.6.2 using:</p> <pre><code>g++ -std=c++0x -Wall -Wextra -O3 -fstrict-aliasing -o alias.exe alias.cpp </code></pre> <p><sup>*</sup> Edit: And if not, how could one modify this to be legal?</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.
 

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