Is it safe and/or good practice to do something as the following?
//NewList is a member function of a class
void NewList(int size){
delete[] list; //list is a member variable; an already initialized dynamic array.
list=new ListObject[size];
}
I'm basically discarding the previous array because I will use different data to store in the class, and hence require a new list
to store other information on the new data. If this is not good practice, what's the alternative?
If delete is applied to one of the pointers, then the object's memory is returned to the free store. If we subsequently delete the second pointer, then the free store may be corrupted.
The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).
Here, the implementation of delete does not have a pointer to which it can null out.
The answer is nothing happens.
It depends. Every time you create an object with new, you must delete it after use. In the given function you are deleting to create a new one, but are you also deleting once you are done with the object? It's safer to create your object and have the system delete it when the object is out of scope.
I would avoid if possible as you can create a memory leak if not deleted appropriately.
Yes, it's totally fine to reuse a pointer to store a new memory address after deleting the previous memory it pointed to.
Just be careful not to dereference the old memory address which is still stored in the pointer. In your code snippet that's not a problem though.
As a side note, most of the time, you should use std::vector
if you want a dynamically-allocated array, as mentioned in the comments.
There is nothing inherently wrong with what you're doing. However, if it is a member function of a class, and list
is a member variable, be aware that the code you have is not exception safe.
In other words, if the call to new[]
fails for some reason, your list
array has been destroyed, and you can't recover the data.
Better to do this:
void NewList(int size)
{
ListObject* temp = new ListObject[size];
delete[] list;
list = temp;
}
If the call to new[]
throws an exception, you haven't destroyed your original data.
However, all of this is taken care of if you used std::vector
, as others have suggested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With