Reusing a pointer after `delete`

Is it safe and / or good practice to do something as follows?

//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 basically discard the previous array, because I will use different data to store in the class and, therefore, will require a new list to store other information about the new data. If this is not good practice, what is the alternative?

+5
source share
3 answers

It depends. Each time you create an object with a new one, it should be deleted after use. In this function, you delete the creation of a new one, but do you also delete as soon as you finish with the object? It is safer to create your own object and delete it when the object goes beyond the scope.

I would avoid if this was possible, since you could create a memory leak if it is not properly removed.

+3
source

Yes, you can completely reuse the pointer to save the new memory address after deleting the previous memory that it pointed to.

Just be careful not to dereference the old memory address, which is still stored in the pointer. In your code snippet, this is not a problem.

As a side note, most of the time you should use std::vector if you need a dynamically allocated array, as indicated in the comments.

+2
source

There is nothing inherently wrong with what you do. However, if it is a member function of a class, and list is a member variable, keep in mind that the code you have is not safe.

In other words, if for some reason the new[] call failed, your list array has been destroyed and you cannot restore the data.

Better to do it:

 void NewList(int size) { ListObject* temp = new ListObject[size]; delete[] list; list = temp; } 

If calling new[] throws an exception, you have not destroyed the original data.

However, all this will take care if you used std::vector , as others suggested.

+1
source

Source: https://habr.com/ru/post/1212854/


All Articles