I'm having a little difficulty understanding the correct sequence of events that should happen when using the delete operator in C++. I've internalized that the proper way to use this is when a pointer is still referencing a pointee.
In the example below - I copy the contents of the array into temp and then delete [] the old array my arrayPointer was pointing too.
I then point the arrayPointer to the newly created array and set the no longer needed temp to nullptr. I want to make sure I'm not causing memory leaks by not deleting the temp pointer. Does this still need to happen?
I ask because I've seen examples where we point to nullptr first then delete but that seems counterintuitive. Any guidance would be greatly appreciated. Thanks!
template <class T>
void ValSet<T>::add(T elementToAdd){
if(!this->contains(elementToAdd)){
if(sizeOfArray == numOfElements){
sizeOfArray *= 2;
T* temp = new T[sizeOfArray];
for (int i = 0; i < numOfElements; i++)
temp[i] = arrayPointer[i];
delete [] arrayPointer;
arrayPointer = temp;
temp = nullptr;
}
numOfElements += 1;
arrayPointer[numOfElements-1] = elementToAdd;
}
}