• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_SCOPED_VECTOR_H_
6 #define BASE_SCOPED_VECTOR_H_
7 
8 #include <vector>
9 
10 #include "base/logging.h"
11 #include "base/stl_util-inl.h"
12 
13 // ScopedVector wraps a vector deleting the elements from its
14 // destructor.
15 template <class T>
16 class ScopedVector {
17  public:
18   typedef typename std::vector<T*>::iterator iterator;
19   typedef typename std::vector<T*>::const_iterator const_iterator;
20 
ScopedVector()21   ScopedVector() {}
~ScopedVector()22   ~ScopedVector() { reset(); }
23 
24   std::vector<T*>* operator->() { return &v; }
25   const std::vector<T*>* operator->() const { return &v; }
26   T* operator[](size_t i) { return v[i]; }
27   const T* operator[](size_t i) const { return v[i]; }
28 
empty()29   bool empty() const { return v.empty(); }
size()30   size_t size() const { return v.size(); }
31 
begin()32   iterator begin() { return v.begin(); }
begin()33   const_iterator begin() const { return v.begin(); }
end()34   iterator end() { return v.end(); }
end()35   const_iterator end() const { return v.end(); }
36 
push_back(T * elem)37   void push_back(T* elem) { v.push_back(elem); }
38 
get()39   std::vector<T*>& get() { return v; }
get()40   const std::vector<T*>& get() const { return v; }
swap(ScopedVector<T> & other)41   void swap(ScopedVector<T>& other) { v.swap(other.v); }
release(std::vector<T * > * out)42   void release(std::vector<T*>* out) {
43     out->swap(v);
44     v.clear();
45   }
46 
reset()47   void reset() { STLDeleteElements(&v); }
48 
49  private:
50   std::vector<T*> v;
51 
52   DISALLOW_COPY_AND_ASSIGN(ScopedVector);
53 };
54 
55 #endif  // BASE_SCOPED_VECTOR_H_
56