Ocean's profile君子不器BlogListsGuestbookMore ![]() | Help |
|
7/23/2008 Using STLRule 1:You can create STL containers that store either objects or pointer to objects. class TMyClass; 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 { 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; 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; However, if you are storing pointers into the container, then the previous code fragment has to be modified to the following: TMyClassList::iterator it; Rule 5:Removing items from the container is done in the following way: TMyClassList::iterator it; Additional line to delete the pointer to the object is needed since the container will not delete a stored pointer so it has to be manually deleted. |
|
|