Lets say i want to resize an array of int pointers, i have a function that looks like this
template<typename T>
static void Resize(T* arr, UINT oldsize, UINT newsize) {
T* ret = new T [newsize];
memcpy(ret, arr, sizeof(arr[0]) * oldsize);
delete[] arr;
arr = ret;
};
The problems begin when i try and resize an array of elements that were created with the “new” keyword (even though the data itself inside the class is POD) because the delete[] triggers their deconstructor which then leaves the new array with pointers to objects that dont exist anymore. So.. even though the objects were created with “new”, cant i just use the free command to get rid of the old array? or somehow delete the array without triggering the deconstructor of each member?
Use a
std::vector.EDIT: by popular demand, an explanation of why the OP’s code does not work.
The code:
Here
arris a pointer passed by value. Assigning toarrat the end only updates the local copy of the actual argument. So after this the actual argument, in the calling code, points to an array that has beendeleted, whith pretty catastrophic result!It could be sort of rescued by passing that pointer by reference:
But this is still pretty fragile code.
For example, the caller needs to keep track of the array size.
With a
std::vectorcalleda, the resize call would instead look likeand in contrast to the DIY solution, when
newSizeis larger, those extra elements of the vector are nulled (which is a bit safer than leaving them as indeterminate values).A
std::vectorcan be indexed just like a raw array. See your C++ textbook about more details of how to use it. If you don’t already have a C++ textbook, do get one: for most people it’s just an impractical proposition to learn C++ from articles and Q/A on the web.