Object Destruction
All objects inheriting from class
RWCollectable inherit a virtual destructor. Hence, the actual type of the object need not be known until run time in order to delete the object. This allows all items in a collection to be deleted without knowing their actual type.
As with any C++ class, objects inheriting from
RWCollectable may need a destructor to release the resources they hold. In the case of
Bus, the names of passengers and customers are
RWCollectableStrings that were allocated off the heap. Hence, they must be reclaimed. Because these strings never appear outside the scope of the class, we do not have to worry about the user having access to them. Hence, we can confidently delete them in the destructor, knowing that no dangling pointers will be left.
Furthermore, because the set pointed to by customers_ is a superset of the set pointed to by passengers_, it is essential that we delete only the contents of customers_.
Here is a possible definition:
Bus::~Bus() {
customers_.clearAndDestroy();
delete passengers_;
}
Note that the language guarantees that it is okay to call delete on the pointer passengers_ even if it is nil. See Section 18.4.1.1.13p1 of the C++ Standard.