Updated documentation.
[kdbg.git] / kdbg / valarray.h
blob37712a91822cfb525a76c2446e71ae659bb497d9
1 // $Id$
3 // Copyright by Johannes Sixt
4 // This file is under GPL, the GNU General Public Licence
6 // an array template class that holds values (not pointers to values)
8 #ifndef VALARRAY_H
9 #define VALARRAY_H
11 // need a placement new
12 #include "config.h"
13 #ifdef HAVE_PLACEMENT_NEW
14 #include <new>
15 #else
16 inline void* operator new(size_t, void* p) { return p; }
17 #endif
19 template<class T>
20 class ValArray
22 public:
23 ValArray() : m_pData(0), m_size(0), m_space(0) { }
24 ~ValArray();
25 void operator=(const ValArray<T>& src);
26 const T& operator[](int i) const { return m_pData[i]; }
27 T& operator[](int i) { return m_pData[i]; }
28 void setSize(int newSize);
29 int size() const { return m_size; }
30 void append(const T& newElem, int count = 1) { expand(newElem, m_size+count); }
32 protected:
33 T* m_pData;
34 int m_size;
35 int m_space;
37 void expand(const T& newElem, int newSize);
40 template<class T>
41 ValArray<T>::~ValArray()
43 setSize(0);
44 delete[] reinterpret_cast<char*>(m_pData);
47 template<class T>
48 void ValArray<T>::operator=(const ValArray<T>& src)
50 setSize(src.size());
51 for (int i = 0; i < src.size(); i++) {
52 m_pData[i] = src.m_pData[i];
56 template<class T>
57 void ValArray<T>::setSize(int newSize)
59 if (newSize == m_size) return;
60 if (newSize > m_size) {
61 expand(T(), newSize);
62 } else {
63 do {
64 m_size--;
65 m_pData[m_size].~T();
66 } while (m_size > newSize);
70 template<class T>
71 void ValArray<T>::expand(const T& newElem, int newSize)
73 if (newSize > m_space) {
74 // reallocate
75 int newSpace = m_space + m_space;
76 if (newSpace < 8) newSpace = 8;
77 if (newSpace < newSize) newSpace = newSize;
78 T* newData = reinterpret_cast<T*>(new char[newSpace * sizeof(T)]);
79 // care about exception safety as much as possible
80 // copy-construct the elements into the new array
81 // TODO: clean up when exception is thrown here
82 for (int i = 0; i < m_size; i++) {
83 new(&newData[i]) T(m_pData[i]);
85 // replace the pointer
86 T* oldData = m_pData;
87 m_pData = newData;
88 m_space = newSpace;
89 // destruct the old data
90 for (int i = m_size-1; i >= 0; i--) {
91 oldData[i].~T();
93 delete[] reinterpret_cast<char*>(oldData);
95 // copy the new element into the new space
96 while (m_size < newSize) {
97 new(&m_pData[m_size]) T(newElem);
98 m_size++;
102 #endif // VALARRAY_H