Archived

This topic is now archived and is closed to further replies.

Spencer

Does stl::vector.clear() call the destructors..

Recommended Posts

Hi! Does if i call vector.clear() on an STL vector, will it call the destructors och the objects it is holding or will it just set its size to zero? thnx --Spencer "Relax, this dragon is sleeping..."

Share this post


Link to post
Share on other sites
Yes, std::vector<T>::clear will erase all of the objects allocated by (in) the vector - all of the Ts.

You could have tested it with a "talking destructor":

class foo
{
public:
...
~foo() {
std::cout << "~foo()" << std::endl;
}
};

int main() {
std::vector<foo> bar;
...
bar.push_back(...);
// etc.

...
bar.clear();

return 0;
}

You need to take a little more care if you have a vector of pointers, though.

[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

Share this post


Link to post
Share on other sites
Note: If you are storing pointers in the vector it will not delete the objects' memory, giving you a memory leak.

you will need to do something like this:

std::vector<*foo> bar;
...
for (vector<*foo>::iterator itr = bar.begin(); itr != bar.end(); )
{
delete (*itr);
itr = bar.erase(itr);
}


[edited by - TheDarkening on October 6, 2003 6:33:16 PM]

Share this post


Link to post
Share on other sites
Although,

while (!bar.empty()) {
   delete bar.back();  bar.pop_back();
}

is more elegant, in my opinion. You could also use a generic unary functor like this:

class single_delete
{
public:
   template <typename T>
   void operator()(T*& ptr) const
   {
      delete ptr;
      ptr = 0; // if you want
   }
};

with std::for_each, defined in algorithm:

std::for_each(bar.begin(), bar.end(), single_delete());


[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]

[edited by - Lektrix on October 7, 2003 12:13:50 PM]

Share this post


Link to post
Share on other sites