]> git.decadent.org.uk Git - videolink.git/blob - auto_array.hpp
Brought documentation up to date.
[videolink.git] / auto_array.hpp
1 // Copyright 2005 Ben Hutchings <ben@decadent.org.uk>.
2 // See the file "COPYING" for licence details.
3
4 #ifndef INC_AUTO_ARRAY_HPP
5 #define INC_AUTO_ARRAY_HPP
6
7 #include <cstddef>
8
9 // Like auto_ptr, but for arrays
10
11 template<typename element_type>
12 class auto_array_ref;
13
14 template<typename element_type>
15 class auto_array
16 {
17     typedef auto_array_ref<element_type> ref_type;
18 public:
19     auto_array()
20             : ptr_(0)
21         {}
22     explicit auto_array(element_type * ptr)
23             : ptr_(ptr)
24         {}
25     auto_array(ref_type other)
26             : ptr_(other.release())
27         {}
28     auto_array & operator=(auto_array & other)
29         {
30             reset(other.release());
31         }
32     ~auto_array()
33         {
34             reset();
35         }
36     element_type * get() const
37         {
38             return ptr_;
39         }
40     element_type * release()
41         {
42             element_type * ptr(ptr_);
43             ptr_ = 0;
44             return ptr;
45         }
46     void reset(element_type * ptr = 0)
47         {
48             delete[] ptr_;
49             ptr_ = ptr;
50         }
51     element_type & operator[](std::ptrdiff_t index)
52         {
53             return ptr_[index];
54         }
55     operator ref_type()
56         {
57             return ref_type(*this);
58         }
59 private:
60     element_type * ptr_;
61 };
62
63 template<typename element_type>
64 class auto_array_ref
65 {
66     typedef auto_array<element_type> target_type;
67 public:
68     explicit auto_array_ref(target_type & target)
69             : target_(target)
70         {}
71     element_type * release()
72         {
73             return target_.release();
74         }
75 private:
76     target_type & target_;
77 };
78
79 #endif // !INC_AUTO_ARRAY_HPP