Reputation: 10137
I have the following function, which is just a constructor. What it does is to allocate memory for a two dimensional, floating pointer array. I was curious to know whether or not, when I add this array to a vector
instance, if I delete the original initialization of the array, will it also delete the array inside the vector as well?
Here's the code:
Evaluator::Evaluator(int row, Column col) {
this->verticies = new std::vector();
float* matrix = NULL;
switch(col) {
case ONE:
matrix = new float[row][1];
break;
case TWO:
matrix = new float[row][2];
break;
case THREE:
matrix = new float[row][3];
break;
case FOUR:
matrix = new float[row][4];
break;
}
this->verticies->push_back(matrix);
delete matrix;
}
Upvotes: 1
Views: 101
Reputation: 308138
Once you delete matrix
, the copy of the pointer that you pushed into the vector is invalid. Any attempt to use those pointers will result in undefined behavior, perhaps crashing the program.
Upvotes: 0
Reputation: 182763
The code's just broken. You can't allocate with new[]
and deallocate with delete
. The implementation is allowed to use completely different logic in the different allocators.
What you want is delete[] matrix;
.
As for the question you asked, it depends what you stored in the vector. If you stored a pointer in the vector and then called delete[]
on that same pointer, the vector holds an invalid pointer. Ouch. If the vector holds objects themselves, then you constructed a new object with the same value as the object you deleted, so the vector is still okay.
Your code isn't compilable and doesn't make clear what the full type of the vector is, so it's hard to say. Also, you should be using smart (or reference-counted) pointers, for just this reason.
Upvotes: 5