simple destructor question

M

michael

Hi All,

if I have a class that uses a STL list of pointers like:

class SomeClass {
private:
list<OtherClass*> aList;
--other stuff--
}

If I just do aList.clear() in the destructor is that sufficient or do I have
to do a delete on each pointer in the list?

Thanks for your help

Michael
 
A

anon

michael said:
Hi All,

if I have a class that uses a STL list of pointers like:

class SomeClass {
private:
list<OtherClass*> aList;
--other stuff--
}

If I just do aList.clear() in the destructor is that sufficient or do I have
to do a delete on each pointer in the list?

You have to delete each pointer. Maybe do it in SomeClass's destructor?
 
K

Keith Davies

anon said:
You have to delete each pointer. Maybe do it in SomeClass's destructor?

Or use a smart pointer of some sort:

class SomeClass {
private:
std::list< boost::shared_ptr< OtherClass > > aList;
};

aList.clear() will do The Right Thing. In fact, you don't even need to
call it in the dtor -- aList is destructed when the SomeClass object
goes away.


Keith
 
M

Mark P

anon said:
You have to delete each pointer. Maybe do it in SomeClass's destructor?

No, it depends what you intend. What we can say for sure is that
clearing (or destructing) the list will not do anything to the objects
pointed to by the contents of that list. Now if you actually intend to
delete each of those objects, then you need to do so explicitly yourself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,301
Messages
2,571,549
Members
48,295
Latest member
JayKillian
Top