title: C++ aliasing rules
body: <p>Just wondering if someone would confirm a few aliasing rules for me.</p>
  
  <p>I know that aliasing (i.e load-store issues) <em>could</em> cause the following type of code to be suboptimal, because we can't assume that <code>x, y, z</code> don't overlap: </p>
  
  <pre><code>// case 1:
  void plus(size_t n, double *x, double *y, double *z)
  {
      for (size_t i = 0; i != n; ++i)
          z[i] = x[i] + y[i];
  } 
  </code></pre>
  
  <p>I know that there's a C keyword <code>__restrict</code> that hints to the compiler that it shouldn't consider the overlapping case, and hence <em>potentially</em> generate better code:</p>
  
  <pre><code>// case 2:
  void plus(size_t n, double *__restrict x, double *__restrict y, double *__restrict z)
  { // as above... }
  </code></pre>
  
  <p>But how does aliasing work with C++ style code, where we would be dealing with container objects passed by reference, rather than the C-like examples above with raw pointers??</p>
  
  <p>For instance, I'm assuming that there would be aliasing issues if we did the following:</p>
  
  <pre><code>// case 3:
  void plus(std::vector&lt;double&gt; &amp;x, std::vector&lt;double&gt; &amp;y, std::vector&lt;double&gt; &amp;z)
  { // similar to above... }
  </code></pre>
  
  <p>And to move to a less trivial example, does it make any difference if the underlying data types in the containers are different?? At the implementation level most containers dynamically manage storage with pointers, so it's not clear to me how the compiler could ensure that the following doesn't alias:</p>
  
  <pre><code>// case 4:
  void foo(std::vector&lt;mytype1&gt; &amp;x, std::vector&lt;mytype2&gt; &amp;y)
  { // interwoven operations on x, y... }
  </code></pre>
  
  <p>I'm not trying to micro-optimise, but I'm wondering if it's currently better to pass restricted pointers to containers around, rather than references.</p>
  
  <p>EDIT: To clear up some terminology, as pointed out: <code>restrict</code> is the C99 keyword. There's also <code>__restrict</code> and <code>__restrict__</code> in various compilers, but they all do the same thing.</p>