Deleting objects from template list
I have a template list say,
List<SuperClass*>* mList;
for(int i = 0;i < mList->ElementsCount();i++)
mList->DeleteElementAtIndex(i);
in mList objects of subclasses are added.
While on deleting object from the list, should I need to开发者_JS百科 convert the object into corresponding subclasses and call the delete method?
No, calling the delete
operator on each pointer without explicit conversion is enough, but you must make sure that the destructors of the classes in the class hierarchy are declared as virtual
(it's enough to mark just the one of the base class as such). In this way, the call to the destructor will be a virtual call, so the correct destructor will be called.
If you don't declare the destructor as virtual, when calling delete
on each pointer the destructor of the base class will be called instead of the correct one; this is the motivation why it's considered almost always an error to have class hierarchies without a virtual
destructor.
More info about this can be found in the relevant entry of the C++ FAQ Lite.
By the way, that list doesn't seem to be an STL list (std::list
), if so you should remove the STL tag from your question.
精彩评论