Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomatically adding and removing an object from a list
    primarykey
    data
    text
    <p>I have a class. When this class is instantiated, I want the instance added to a list. When the object is deleted, I want it removed from the list.</p> <p>So I give the object a shared pointer to itself. I then have a list of weak pointers to those shared pointers. When an object is created, it creates a shared pointer to itself, makes a weak pointer to that, and puts the weak pointer in a list.</p> <p>When the object is destroyed, the shared pointer is as well. Whenever I try to access a member in the list, I ensure that it hasn't expired and that its use count isn't 0. Despite this, I still crash when the list member is destroyed. Why? Can I get around it? Here's my SSCCE:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;vector&gt; class test { private: std::shared_ptr&lt;test&gt; self; public: int val; test(int set); test(test &amp;copy) = delete; // making sure there weren't issues // with a wrong instance being deleted }; std::vector&lt;std::weak_ptr&lt;test&gt;&gt; tests; test::test(int set): val(set) { this-&gt;self = std::shared_ptr&lt;test&gt;(this); tests.push_back(std::weak_ptr&lt;test&gt;(this-&gt;self)); } void printTests() { for (auto i = tests.begin(); i != tests.end(); i++) { if (i-&gt;use_count() == 0 || i-&gt;expired()) { tests.erase(i); continue; } std::cout &lt;&lt; i-&gt;lock()-&gt;val &lt;&lt; std::endl; } std::cout &lt;&lt; std::endl; } int main(int argc, char **argv) { { test t(3); std::cout &lt;&lt; "First tests printing: " &lt;&lt; std::endl; printTests(); } // SEGFAULTS HERE std::cout &lt;&lt; "Second tests printing: " &lt;&lt; std::endl; printTests(); return 0; } </code></pre> <p>The output of this program is as follows: </p> <pre><code>First tests printing: 3 Segmentation fault (core dumped) </code></pre>
    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.
 

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