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)
11 // need a placement new
13 #ifdef HAVE_PLACEMENT_NEW
16 inline void* operator new(size_t, void* p
) { return p
; }
23 ValArray() : m_pData(0), m_size(0), m_space(0) { }
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
); }
37 void expand(const T
& newElem
, int newSize
);
41 ValArray
<T
>::~ValArray()
44 delete[] reinterpret_cast<char*>(m_pData
);
48 void ValArray
<T
>::operator=(const ValArray
<T
>& src
)
51 for (int i
= 0; i
< src
.size(); i
++) {
52 m_pData
[i
] = src
.m_pData
[i
];
57 void ValArray
<T
>::setSize(int newSize
)
59 if (newSize
== m_size
) return;
60 if (newSize
> m_size
) {
66 } while (m_size
> newSize
);
71 void ValArray
<T
>::expand(const T
& newElem
, int newSize
)
73 if (newSize
> m_space
) {
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
89 // destruct the old data
90 for (int i
= m_size
-1; i
>= 0; i
--) {
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
);