Destructor

closed account (oj2wbRfi)
I created this class..
1
2
3
4
5
6
7
8
9
10
11
12
13

class War {

private:

string place;
list <soldier*> soldiers; // list with pointer soldier for all soldiers

public:
War (){ place = ""; } //
War(ifstream & inn); // constructure to read all data from file 
~War (); //??????? I need here to create destructor to delete all soldiers from //the list 
}; 
Simply iterate over the list, deleting each element in turn.

If you don't know how to do those things, a simple search for "C++ list tutorial" will provide you with some learning resources.
@George P, the empty() function tells you whether the list is empty or not. It does not call delete or remove any elements in the list.
@Peter87, the example code for empty() at the link shows how to use it to delete/remove the list's elements.

Using a loop allows for any special handling the list's individual elements might require.

Just as MikeyBoy suggested.

Ivanka can add a similar loop to the class dtor and purge the data member list's elements.

There's also std::link::clear that will remove all the elements at once, destroying them.
http://www.cplusplus.com/reference/list/list/clear/

Without knowing how the elements are created and therefore should be destroyed using a loop based on whether a list is empty isn't a bad choice for clearing a list.

[ETA]: If the list is used to store pointers of objects created on the heap I'd personally use smart pointers over raw pointers & new/delete. That way when the class dtor is called the list's contents are automatically destroyed as well as the class object goes out of scope. No messy details of manual memory management.
Last edited on
The STL <list> is destroyed automatically so doesn't have to be treated or even mentioned in the destructor.

If the elements (whether they are pointers or objects) are to be de-listed then the List::erase() and/or List::clear() functions apply right up to and including the point where List::empty() indicates there are no more elements.

If the elements have been initiated by using 'new' inside or outside the class then they should be considered carefully for getting the normal 'delete' treatment to avoid memory leaks.
Topic archived. No new replies allowed.