Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Realize that smart pointers are compared by comparing the underlying container. So you can just use a <code>std::set</code> of whatever smartpointer you prefer. Personally I use <code>std::unique_ptr</code> over <code>shared_ptr</code>, whenever I can get away with it, since it makes the ownership much clearer (whoever holds the <code>unique_ptr</code>is the owner) and has much lower overhead too. I have found that this is enough for almost all my code. The code would look something like the following:</p> <pre><code>std::set&lt;std::unique_ptr&lt;T&gt; &gt; _list; void SomeClass::add(T* ptr) { std::unique_ptr&lt;T&gt; p(ptr); auto iter = _list.find(p); if(iter == _list.end()) _list.insert(std::move(p)); else p.release(); } </code></pre> <p>I'm not sure right now if that is overkill (have to check if <code>insert</code> is guaranteed not to do anything, if the insertion fails), but it should work. Doing this with <code>shared_ptr&lt;T&gt;</code> would look similar, although be a bit more complex, due to the lack of a <code>relase</code> member. In that case I would probably first construct a <code>shared_ptr&lt;T&gt;</code> with a do nothing <code>deleter</code> too pass to the call to find and then another <code>shared_ptr&lt;T&gt;</code> which is actually inserted.</p> <p>Of course personally I would avoid doing this and always pass around smart pointers when the ownership of a pointer changes hands. Therefore I would rewrite <code>SomeClass::add</code> as <code>void SomeClass::add(std::unique_ptr&lt;T&gt; ptr)</code> or <code>void SomeClass::add(std::shared_ptr&lt;T&gt; ptr)</code> which would pretty much solve the problem of having multiple instances anyways (as long as the pointer is always wrapped).</p>
 

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