Re: STL destruction question...
On 21 Apr, 01:30, "barcaroller" <barcarol...@music.net> wrote:
"Ian Collins" <ian-n...@hotmail.com> wrote in message
news:58t3hhF2i6eqtU23@mid.individual.net...
barcaroller wrote:
When a STL container is destroyed, will the destructor of the individual
objects be automatically called?
Yes, assuming they have one!
Does this also apply to object pointers (e.g. set<Class*>)? In this case I
would create the object myself (using 'new Class')
That's one way of obtaining a Class*. Another way is to take the
address of an existing Class object - which may or may not have
dynamic storage duration (i.e. may or may not need delete'ing).
but I assume that, since
I created it, I should destroy it.
Absolutely.
However, there's no reason why the STL
container could not do that for me (by calling delete for each object).
STL containers could have been designed that way. But such behaviour
would rule out the possibility of storing pointers to anything other
than dynamically allocated memory. The code below would be broken -
something of a restriction on the way STL containers could be used.
#include <vector>
void foo()
{
int i = 42;
int* pi = &i;
std::vector<int*> v;
v.push_back(pi);
}
Would it?
Nope. The library designers opted not to impose the above restriction
on client code. You were right in your first assumption.
If you are storing pointers to dynamically allocated objects, you can
make your life easier by storing smart pointers that manage the delete
automatically. Boost has examples and I believe some are included in
std::tr1 if your compiler supports it.
Gavin Deane