Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>With the update to the question, I think I can see what the problem is =)</p> <p>In your initial <code>swap()</code> function, you had these lines:</p> <pre><code>swap(first._memory, second._memory); swap(first._ptr, second._ptr); swap(first._len, second._len); </code></pre> <p>If these were exrefs, all was well and good - swap would be executed as planned. However, if one was an inref (for now, we'll use the example you provided), then this was going on:</p> <p>In these lines:</p> <pre><code>MemRef mr_a; // creates a memref with _ptr(NULL), _len(0) mr_a = "woof"; </code></pre> <p>as you said correctly, a temporary <strong>inref</strong> was created from "woof", with its <code>_ptr</code> variable pointing to the beginning of <code>_memory.c_str()</code>.</p> <p>Now, when your <code>swap()</code> gets called, first this happens:</p> <pre><code>swap(first._memory, second._memory); </code></pre> <p>So far all good. You've swapped the strings - but their <strong>addresses</strong> haven't changed, only their <strong>contents</strong>. From the standard: </p> <p><code>References, pointers, and iterators referring to the elements of a basic_string sequence may be invalidated by the following uses of that basic_string object: — As an argument to non-member functions swap()...</code> <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf" rel="nofollow">C++ International Standard n1905</a></p> <p>So now, during the line</p> <pre><code>swap(first._ptr, second._ptr); </code></pre> <p>you introduce the prolem. Those are pointing to somewhere undefined - by swapping the string, we <strong>invalidate</strong> any pointers/iterators/references to the string or its members, including c_str() - but we <strong>definitely</strong> don't swap the nemory locations. So, swapping the pointers is wrong in this case, as you realized.</p> <p>Fortunately, you've already solved the problem - by resetting the pointers in the case of an inref instead of swapping them, you avoid pointing to invalidated memory locations, and all problems are resolved! Hopefully this clears up what was going on though =) </p> <p>edit: added standard reference and clarified!</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.
 

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