Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You've missed a significant optimization in your copy assignment operator. And subsequently the situation has gotten confused.</p> <pre><code> AnObject&amp; operator = ( const AnObject&amp; rh ) { if (this != &amp;rh) { if (n != rh.n) { delete [] a; n = 0; a = new int [ rh.n ]; n = rh.n; } std::copy(rh.a, rh.a+n, a); } return *this; } </code></pre> <p>Unless you really <em>never</em> think you'll be assigning <code>AnObject</code>s of the same size, this is much better. Never throw away resources if you can recycle them.</p> <p>Some might complain that the <code>AnObject</code>'s copy assignment operator now has only basic exception safety instead of strong exception safety. However consider this:</p> <blockquote> <p>Your clients can always take a fast assignment operator and give it strong exception safety. But they can't take a slow assignment operator and make it faster.</p> <pre><code>template &lt;class T&gt; T&amp; strong_assign(T&amp; x, T y) { swap(x, y); return x; } </code></pre> </blockquote> <p>Your move constructor is fine, but your move assignment operator has a memory leak. It should be:</p> <pre><code> AnObject&amp; operator = ( AnObject&amp;&amp; rh ) { delete [] a; n = rh.n; a = rh.a; rh.n = 0; rh.a = nullptr; return *this; } </code></pre> <p>...</p> <blockquote> <pre><code>Data a = MakeData(); Data c = 5 * a + ( 1 + MakeMoreData() ) / 3; </code></pre> <p><strong>q2:</strong> Using a combination of copy elision / RVO / move semantics the compiler should be able to this this with a minimum of copying, no?</p> </blockquote> <p>You may need to overload your operators to take advantage of resources in rvalues:</p> <pre><code>Data operator+(Data&amp;&amp; x, const Data&amp; y) { // recycle resources in x! x += y; return std::move(x); } </code></pre> <p>Ultimately resources ought to be created exactly once for each <code>Data</code> you care about. There should be no needless <code>new/delete</code> just for the purpose of moving things around.</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