blob: 5fcf089bf4b83003672481bded8cec89eadaf98a [file] [log] [blame]
Carl Shapiro58551df2011-07-24 03:09:51 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
3#ifndef ART_SRC_STL_UTIL_H_
4#define ART_SRC_STL_UTIL_H_
5
6namespace 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.
18template <class ForwardIterator>
19void 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.
38template <class T>
39void STLDeleteElements(T *container) {
40 if (!container) return;
41 STLDeleteContainerPointers(container->begin(), container->end());
42 container->clear();
43}
44
Elliott Hughesc31664f2011-09-29 15:58:28 -070045// Given an STL container consisting of (key, value) pairs, STLDeleteValues
46// deletes all the "value" components and clears the container. Does nothing
47// in the case it's given a NULL pointer.
48template <class T>
49void STLDeleteValues(T *v) {
50 if (!v) return;
51 for (typename T::iterator i = v->begin(); i != v->end(); ++i) {
52 delete i->second;
53 }
54 v->clear();
55}
56
Carl Shapiro58551df2011-07-24 03:09:51 -070057} // namespace art
58
59#endif // ART_SRC_STL_UTIL_H_