Reputation: 427
I am trying to implement an insert() function that should insert a value into a boolean array and set the index equal to that value to 'true'. The IntSet
object has a pointer, value
, to an array of booleans and an int, size
, to hold the size of the array. So IntSet A(2, 4, 10);
will create an array of size 10 and the indexes at 2, 4, 10 will be set to true.
The insert() function returns true or false depending on if it inserted the value or not, and it should resize the array if the inserted value is larger than the size of the array. So, A.insert(1000);
would resize the array to size 1001 and set the value at index 1000 to true.
My issue is with deleting the old array pointer and setting it to the new, resized array. No matter what I do, it always breaks at the delete[], and I'm not sure why.
This is what I have so far:
bool IntSet::insert(int toInsert) {
int tempSize = this->size;
// if toInsert is greater than the number of elements in the array, call
// copy constructor and assign new value to true
if(toInsert < this->size && toInsert >= 0) {
value[toInsert] = true;
return true;
}
IntSet largerSet(toInsert+1);
if(toInsert > this->size+1) {
for(int i = 0; i < largerSet.size+1; i++) {
largerSet.value[i] = false;
}
largerSet.value[toInsert] = true;
for(int i = 0; i < tempSize+1; i++) {
if(this->value[i] != false) {
largerSet.value[i] = true;
}
}
std::swap(value, largerSet.value);
std::swap(size, largerSet.size);
}
return true;
}
EDIT: used swap to move value to current array.
I hope I was clear enough in my explanation, if you need more clarification I'm happy to provide more code. This is for a class assignment, so I'm not expecting a direct answer, but anything that can point me to the right direction will help immensely.
Thanks all!
Upvotes: 0
Views: 1361
Reputation: 7637
You should leave allocations to constructors, deallocations to destructors, copies to copy constructors and copy assignment operators. You now have a function that does a little bit of everything.
A clean way to reallocate is first to provide a swap
function (that swaps your pointer + size); given that, create a temporary of the new size (like largerSet
), initialize the new data, then swap your set with largerSet
. As the temporary goes out of scope, it gets destroyed, and delete[]
is called automatically.
Now when largerSet
goes out of scope, largerSet.value
gets deleted (I assume this is done in your destructor), but this now equals value
, so your data are gone.
Upvotes: 1