Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Update:</strong> Using a <code>std::unique_ptr</code> as a holder for the container is the canonical generic solution - simply don't move the container, just transfer the ownership and swap the iterators. As you already said you can special-case this as an optimization, although I'd expect the generic solution to be also quite efficient and I'd only accept more complexity (aka bug-potential) to the code after proving that it's a real performance win for your use-case.</p> <p>I'll leave the former answer below for future readers: Read it and the comments to see why other solutions are not really working and in which cases they cause trouble.</p> <hr> <p>The obvious way to update the iterator would be:</p> <pre><code>Container c = ...; Container::iterator it = ...; const auto d = std::distance( c.begin(), it ); Container n = std::move(c); it = n.begin(); std::advance( it, d ); </code></pre> <p>which is generally linear, but constant when the iterator is a random access iterator.</p> <p>Since you probably don't want to do that, you have two options which should help: Either default construct the new container and use <code>swap</code> without invalidating the iterators or put the container into a <code>std::unique_ptr</code> and move that instead.</p> <p>The first approach (<code>swap</code>) requires both instances to have the container instance and this might be a bit larger than the simple, single pointer stored inside a <code>std::unique_ptr</code>. When you move your instances around very often, the <code>std::unique_ptr</code>-based approach seems preferable to me, although each access requires one more pointer indirection. Judge (and measure) for yourself what fits best in your case.</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