COMMON: Change Array::insert_aux to immediately assign newly allocated memory to _storage

This commit is contained in:
Max Horn 2011-05-16 13:58:59 +02:00
parent 85d5eec950
commit eedb2d721f

View file

@ -238,15 +238,15 @@ public:
if (newCapacity <= _capacity) if (newCapacity <= _capacity)
return; return;
T *old_storage = _storage; T *oldStorage = _storage;
_capacity = newCapacity; _capacity = newCapacity;
_storage = new T[newCapacity]; _storage = new T[newCapacity];
assert(_storage); assert(_storage);
if (old_storage) { if (oldStorage) {
// Copy old data // Copy old data
copy(old_storage, old_storage + _size, _storage); copy(oldStorage, oldStorage + _size, _storage);
delete[] old_storage; delete[] oldStorage;
} }
} }
@ -286,29 +286,28 @@ protected:
const uint n = last - first; const uint n = last - first;
if (n) { if (n) {
const uint idx = pos - _storage; const uint idx = pos - _storage;
T *newStorage = _storage; T *oldStorage = _storage;
if (_size + n > _capacity) { if (_size + n > _capacity) {
// If there is not enough space, allocate more and // If there is not enough space, allocate more and
// copy old elements over. // copy old elements over.
uint newCapacity = roundUpCapacity(_size + n); uint newCapacity = roundUpCapacity(_size + n);
newStorage = new T[newCapacity]; _storage = new T[newCapacity];
assert(newStorage); assert(_storage);
copy(_storage, _storage + idx, newStorage); copy(oldStorage, oldStorage + idx, _storage);
pos = newStorage + idx; pos = _storage + idx;
} }
// Make room for the new elements by shifting back // Make room for the new elements by shifting back
// existing ones. // existing ones.
copy_backward(_storage + idx, _storage + _size, newStorage + _size + n); copy_backward(oldStorage + idx, oldStorage + _size, _storage + _size + n);
// Insert the new elements. // Insert the new elements.
copy(first, last, pos); copy(first, last, pos);
// Finally, update the internal state // Finally, update the internal state
if (newStorage != _storage) { if (_storage != oldStorage) {
delete[] _storage; delete[] oldStorage;
_capacity = roundUpCapacity(_size + n); _capacity = roundUpCapacity(_size + n);
_storage = newStorage;
} }
_size += n; _size += n;
} }