Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ pointer container with reference counting
    text
    copied!<p>I need a collection in which i can store heap-allocated objects having virtual functions.</p> <p>I known about <code>boost::shared_ptr</code>, <code>std::unique_ptr</code> (C++11) and <code>boost::ptr_(vector|list|map)</code>, but they doesn't solve duplicate pointer problem.</p> <p>Just to describe a problem - i have a function which accepts heap-allocated pointer and stores it for future use:</p> <pre><code>void SomeClass::add(T* ptr) { _list.push_back(ptr); } </code></pre> <p>But if i call <code>add</code> twice with same parameter <code>ptr</code> - <code>_list</code> will contain two pointers to same object and when <code>_list</code> is destructed multiple deletion of same object will occur.</p> <p>If <code>_list</code> will count pointer which he stores and uses them at deletion time then this problem will be solved and objects will not be deleted multiple times.</p> <p><strong>So the question is:</strong></p> <p>Does somebody knows some library with collections (vector,list,map in essence) of pointer with auto-delete on destruction and support of reference counting?</p> <p>Or maybe i can solve this problem using some other technique?</p> <p><strong>Update:</strong></p> <p>I need support of duplicate pointers. So i can't use <code>std::set</code>.</p> <p>As <a href="https://stackoverflow.com/a/8774779/809107">Kerrek SB</a> and <a href="https://stackoverflow.com/a/8774799/809107">Grizzly</a> mentioned - it is a bad idea to use raw pointers in general and suggests to use <code>std::make_shared</code> and forget about instantiation via <code>new</code>. But this is responsibility of client-side code - not the class which i designs. Even if i change <code>add</code> signature (and <code>_list</code> container of course) to</p> <pre><code>void SomeClass::add(std::shared_ptr&lt;T&gt; ptr) { _list.push_back(ptr); } </code></pre> <p>then somebody (who doesn't know about <code>std::make_shared</code>) still can write this:</p> <pre><code>SomeClass instance; T* ptr = new T(); instance.add(ptr); instance.add(ptr); </code></pre> <p>So this is not a full solution which i wait, but useful if you write code alone.</p> <p><strong>Update 2:</strong></p> <p>As an alternative solution i found a clonning (using generated copy constructor). I mean that i can change my <code>add</code> function like this:</p> <pre><code>template &lt;typename R&gt; void SomeClass::add(const R&amp; ref) { _list.push_back(new R(ref)); } </code></pre> <p>this will allow virtual method (R - class which extends some base class (interface)) calls and disallow duplicate pointers. But this solution has an overhead for clone.</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