Carl Shapiro | 58551df | 2011-07-24 03:09:51 -0700 | [diff] [blame] | 1 | // Copyright 2011 Google Inc. All Rights Reserved. |
| 2 | |
| 3 | #ifndef ART_SRC_STL_UTIL_H_ |
| 4 | #define ART_SRC_STL_UTIL_H_ |
| 5 | |
| 6 | namespace art { |
| 7 | |
| 8 | // STLDeleteContainerPointers() |
| 9 | // For a range within a container of pointers, calls delete |
| 10 | // (non-array version) on these pointers. |
| 11 | // NOTE: for these three functions, we could just implement a DeleteObject |
| 12 | // functor and then call for_each() on the range and functor, but this |
| 13 | // requires us to pull in all of algorithm.h, which seems expensive. |
| 14 | // For hash_[multi]set, it is important that this deletes behind the iterator |
| 15 | // because the hash_set may call the hash function on the iterator when it is |
| 16 | // advanced, which could result in the hash function trying to deference a |
| 17 | // stale pointer. |
| 18 | template <class ForwardIterator> |
| 19 | void STLDeleteContainerPointers(ForwardIterator begin, |
| 20 | ForwardIterator end) { |
| 21 | while (begin != end) { |
| 22 | ForwardIterator temp = begin; |
| 23 | ++begin; |
| 24 | delete *temp; |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | // STLDeleteElements() deletes all the elements in an STL container and clears |
| 29 | // the container. This function is suitable for use with a vector, set, |
| 30 | // hash_set, or any other STL container which defines sensible begin(), end(), |
| 31 | // and clear() methods. |
| 32 | // |
| 33 | // If container is NULL, this function is a no-op. |
| 34 | // |
| 35 | // As an alternative to calling STLDeleteElements() directly, consider |
| 36 | // ElementDeleter (defined below), which ensures that your container's elements |
| 37 | // are deleted when the ElementDeleter goes out of scope. |
| 38 | template <class T> |
| 39 | void STLDeleteElements(T *container) { |
| 40 | if (!container) return; |
| 41 | STLDeleteContainerPointers(container->begin(), container->end()); |
| 42 | container->clear(); |
| 43 | } |
| 44 | |
| 45 | } // namespace art |
| 46 | |
| 47 | #endif // ART_SRC_STL_UTIL_H_ |