Under what conditions does C++ optimize out constructor calls?
<p>I'm writing a class for Matrix arithmetic, and one feature I'm implementing is that you can "slice" a matrix and get another matrix back, but done such that the returned matrix references the parent's memory.  This is very useful if you want to things like get a subsection of a matrix or add a vector to a column or things like that.  </p>

<p>However, I wanted to implement it so that if the returned matrix is assigned or copied, the aliasing is broken and the memory is copied, so that you can't easily pass an aliased matrix around forever.</p>

<p>In playing with this, I have something like this:</p>

<pre><code>matrix B = A.slice(1,1);  
</code></pre>

<p>A.slice(1,1) returns a sub-matrix of A (offset 1 row and 1 column).  I implemented the = operator to break the aliasing, but to my chagrine, it isn't called when doing this, even with -O0 on.  Similarly:</p>

<pre><code>matrix B(A.slice(1,1)); 
</code></pre>

<p>Doesn't call the copy constructor (also written to break aliasing).  The only thing that works is:</p>

<pre><code>matrix B; B = A.slice(1,1);
</code></pre>

<p>My question is, obviously since I'm initializing B directly from A in the first two examples, it's taking some sort of shortcut, while I explicitly create B first in the last example and <em>then</em> assign A.slice(1,1) to it. </p>

<p>Can someone provide me with some insight into what the rules are in cases like these for when copy constructors and assignment operators are called?</p>
