Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The question is quite vague... but either way, I guess that you are wondering if pointers stored in a <code>vector</code> would automatically be deleted when <code>clear()</code> is called.</p> <p>This is not the case. Whatever you store in a <code>vector</code> will have its destructor called when <code>clear()</code> occurs. And the destructor of a primitive type (such as a pointer) does.. nothing.</p> <p>From my SGI implementation:</p> <pre><code>/** * Erases all the elements. Note that this function only erases the * elements, and that if the elements themselves are pointers, the * pointed-to memory is not touched in any way. Managing the pointer is * the user's responsibilty. */ void clear() { erase(begin(), end()); } </code></pre> <p>To properly delete items pointers in any STL container, the easiest way is to create a functor and apply it on every item:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;vector&gt; #include &lt;functional&gt; #include &lt;algorithm&gt; template &lt;typename ValueT&gt; struct func_delete : public std::unary_function&lt;ValueT,void&gt; { void operator()( ValueT&amp; item ) { delete item; } }; struct Foo { ~Foo() { std::cout &lt;&lt; "Foo::~Foo()" &lt;&lt; std::endl; } }; template &lt;typename ContainerT&gt; void delete_container( ContainerT&amp; container ) { std::for_each( container.begin(), container.end(), func_delete&lt;typename ContainerT::value_type&gt;() ); } int main( int argc, char** argv ) { std::vector&lt;Foo*&gt; foos; foos.push_back( new Foo ); foos.push_back( new Foo ); foos.push_back( new Foo ); // Either of these two lines will work //std::for_each( foos.begin(), foos.end(), func_delete&lt;Foo*&gt;() ); //delete_container( foos ); foos.clear(); return EXIT_SUCCESS; } </code></pre>
 

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