Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is one important reason why it's not enough with the code you proposed:</p> <ul> <li>The assignment operator is applied on a <strong>initialized object</strong>, but this is not the case in the copy constructor. Specifically, your <code>data</code> member is not initialized properly when the code runs <code>*this = array</code> (<code>data</code> isn't in a member-initializer list), so you are calling <code>delete[]</code> operator on the uninitialized <code>data</code>.</li> </ul> <p>It requires you to, at least, use a member-initializer list to initialize the <code>data</code> member before you use it.</p> <p>There are more drawbacks about your propose:</p> <ul> <li>The assignment operator forces restrictions on <code>T</code> type (but maybe that restrictions are in the class <code>Array</code> anyway): <ul> <li><code>T</code> must be default-constructible (as noted by leemes).</li> </ul></li> <li>assignment operator is not good implemented: <ul> <li>is not considering case <code>a = a</code> (self-assignment), as Nick Bougalis noted.</li> </ul></li> <li>is not exception safe: <ul> <li>if <code>new[]</code> operator fails, the object will be in an inconsistent state.</li> <li>if copying <code>T</code> throws an exception, the object will be in an inconsistent state.</li> </ul></li> </ul> <p>I see a much better approach with using the copy constructor in assignment operator implementation instead of the opposite:</p> <pre><code>Array&lt;T, ROW, COL&gt;(const Array&lt;T, ROW, COL&gt; &amp;array): data(new T[ROW * COL]) { for (int i = 0; i &lt; ROW; ++i) { for (int j = 0; j &lt; COL; ++j) { data[j*ROW + i] = other(i, j); } } } Array&lt;T, ROW, COL&gt;&amp; operator=(Array&lt;T, ROW, COL&gt; other) { swap(other); return *this; } void swap(Array&lt;T, ROW, COL&gt;&amp; other) { T* tmp = data; data = other.data; other.data = tmp; } </code></pre> <p>(This is also known as the <strong>copy-and-swap idiom</strong>.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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