Rule 1:
You can create STL containers that store either objects or pointer to objects.
class TMyClass;
typedef list<TMyClass> TMyClassList; // Stores objects into the list container
typedef list<TMyClass*> TMyClassPtrList; // Stores pointers to object into the list container
Usually, list container that stores the object is used. However, if the object is using a machine resource (handle to file, named pipe, socket or similar), then it is more appropriate to use lists that stores pointers to objects.
If the container stores objects, then it is automatically cleaned up during container destruction. However, if it stores pointers to objects, programmer is responsible to delete all pointers.
Rule 2:
Each class (whose instance will go into the container) must implement at least the copy constructor (it is good to implement also the assignment operator.class TMyClass {
private:
...
public:
TMyClass(..);
// Copy constructor
TMyClass(const TMyClass& obj) { *this = obj; }
// Assignment operator
TMyClass& operator=(const TMyClass& obj);
...
};
This is necessary since the STL will create a local copy of the object when you insert an object instance into the container. If you do not write a correct code for the copy constructor, object within a list will have some data members uninitialized.
Rule 3:
Inserting an object into the container is done in the following way:
TMyClass object;
TMyClassList myList;
TMyClassList::iterator it;
it = myList.insert(myList.end(), object);
TMyClass *pObject = &(*it);
Previous example shows how to insert an object into the container and obtain a pointer to the object within container. This is necessary since the container will create a new copy of the "object" instance and the original "object" instance is not used any more. In case you are storing pointers to a list, this is not necessary since original pointer is stored into the container.
Rule 4:
Iterating through container is done in the following way:
TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
pObject = &(*it);
// Use pObject
}
However, if you are storing pointers into the container, then the previous code fragment has to be modified to the following:
TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
pObject = *it;
// Use pObject
}
Rule 5:
Removing items from the container is done in the following way:
TMyClassList::iterator it;
TMyClass *pObject;
for (it = myList.begin(); it != myList.end(); it ++) {
pObject = &(*it);
if (pObject satisfies some delete criteria) then
myList.erase(it);
// If pointers are stored in a list then add
delete pObject;
}