Note that there are some explanatory texts on larger screens.

plurals
  1. PODerived class stored in ptr_vector not being destructed
    text
    copied!<p>Was trying to find the best way to use ptr_vector to store, access and release objects, especially when the stored object is inherited from other (ptr_vector should not have any issues with object slicing). But when running the below program, surprisingly the derived class isn't being destructed. Anyone know why?</p> <pre><code>#include &lt;boost/ptr_container/ptr_vector.hpp&gt; #include &lt;iostream&gt; #include &lt;boost/ptr_container/ptr_map.hpp&gt; #include &lt;boost/foreach.hpp&gt; using namespace std; class A { public: int id; A() {cout&lt;&lt;"Constructed A()"&lt;&lt;endl;} A(int i):id(i) {cout&lt;&lt;"Constructed A"&lt;&lt;i&lt;&lt;endl;} ~A() {cout&lt;&lt;"* Destructed A"&lt;&lt;id&lt;&lt;endl;} }; class B:public A { public: int i; B() {cout&lt;&lt;"Constructed B"&lt;&lt;endl;} B(int ii):i(ii) {id=ii;cout&lt;&lt;"Constructed B"&lt;&lt;i&lt;&lt;endl;} ~B() {cout&lt;&lt;"* Destructed B"&lt;&lt;i&lt;&lt;endl;} }; class zoo { boost::ptr_vector&lt;A&gt; the_animals; public: void addAnimal(A* a) {the_animals.push_back( a );} void removeAnimal(int id) {the_animals.release(the_animals.begin()+id); } void removeOwnership(int id) {the_animals.release(the_animals.begin()+id).release();} }; int main() { zoo z; z.addAnimal( new B(0) ); //delete abc;z.addAnimal(abc);//doing this will cause heap corruption B* lion=new B(1); z.addAnimal(lion); z.removeOwnership(1); delete lion; z.removeAnimal(0); }//main </code></pre> <p>The output for the program is:</p> <pre><code>Constructed A() Constructed B0 Constructed A() Constructed B1 * Destructed B1 * Destructed A1 * Destructed A0 </code></pre> <p>Why isn't B0 being destructed? Did the object get sliced?</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