From 9081ab440242da4e3e7373f0d044c7373f97b5dc Mon Sep 17 00:00:00 2001 From: Max Horn Date: Mon, 16 May 2011 14:21:41 +0200 Subject: COMMON: Unify Array memory allocation We also change how alloc failures are handled: Instead of using assert(), which is usually disabled in release builds on various platforms, we now *always* catch this situation and invoke error() if necessary. --- common/array.h | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) (limited to 'common') diff --git a/common/array.h b/common/array.h index a1db9a6494..26ee2afbcc 100644 --- a/common/array.h +++ b/common/array.h @@ -24,6 +24,7 @@ #include "common/scummsys.h" #include "common/algorithm.h" +#include "common/textconsole.h" // For error() namespace Common { @@ -72,8 +73,7 @@ public: Array(const Array &array) : _capacity(array._size), _size(array._size), _storage(0) { if (array._storage) { - _storage = new T[_capacity]; - assert(_storage); + allocCapacity(_size); copy(array._storage, array._storage + _size, _storage); } } @@ -83,9 +83,8 @@ public: */ template Array(const T2 *data, int n) { - _capacity = _size = n; - _storage = new T[_capacity]; - assert(_storage); + _size = n; + allocCapacity(n); copy(data, data + _size, _storage); } @@ -179,9 +178,7 @@ public: delete[] _storage; _size = array._size; - _capacity = _size; - _storage = new T[_capacity]; - assert(_storage); + allocCapacity(_size); copy(array._storage, array._storage + _size, _storage); return *this; @@ -239,9 +236,7 @@ public: return; T *oldStorage = _storage; - _capacity = newCapacity; - _storage = new T[newCapacity]; - assert(_storage); + allocCapacity(newCapacity); if (oldStorage) { // Copy old data @@ -267,6 +262,13 @@ protected: return capa; } + void allocCapacity(uint capacity) { + _capacity = capacity; + _storage = new T[capacity]; + if (!_storage) + ::error("Common::Array: failure to allocate %d bytes", capacity); + } + /** * Insert a range of elements coming from this or another array. * Unlike std::vector::insert, this method does not accept @@ -290,9 +292,7 @@ protected: if (_size + n > _capacity) { // If there is not enough space, allocate more and // copy old elements over. - uint newCapacity = roundUpCapacity(_size + n); - _storage = new T[newCapacity]; - assert(_storage); + allocCapacity(roundUpCapacity(_size + n)); copy(oldStorage, oldStorage + idx, _storage); pos = _storage + idx; } @@ -307,7 +307,6 @@ protected: // Finally, update the internal state if (_storage != oldStorage) { delete[] oldStorage; - _capacity = roundUpCapacity(_size + n); } _size += n; } -- cgit v1.2.3