Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does delete need to be used for new'd arrays created in vector?

I'm trying to create some dynamic arrays for a void** data array.

std::vector<void*> data;
data.push_back(new double[1024]);  // array of doubles
data.push_back(new short[1024]);   // array of shorts

For clean up should I just use

data.clear();

Or do each of the new(s) need to be deleted and if so, how is that done?

like image 315
codebender Avatar asked Jan 28 '23 20:01

codebender


1 Answers

For clean up should I just use

data.clear();

That will remove all pointers from the vector. If any of those are the only copies that point to their respective dynamic objects, then those objects can no longer be destroyed nor can their memory be released. This is called a memory leak.

Or do each of the new(s) need to be deleted

Yes. For each time a new[] expression is executed, there must be exactly one delete[]. If there is no delete[], then there is a leak.

and if so, how is that done?

You simply delete each pointer. You have to be extra careful to not accidentally overwrite or remove an element of that vector without deleting it first. You must also be careful to not delete same element (or copies of it) more than once.

Also, it is not possible to delete a pointer to void. A pointer to void can be converted to any data pointer type, but you must know the type of each element. A working example

delete[] static_cast<double*>(data[0]);
delete[] static_cast<short* >(data[1]);

It is usually a very bad idea to store bare pointers that own memory - even more so to use pointers to void for that purpose. A better design is to store the dynamic arrays in RAII container such as std::vector:

std::vector<double> doubles(1024);
std::vector<short>  shorts (1024);
std::vector<void*>  data{doubles.data(), shorts.data()};

This way the arrays are owned by vectors, and memory is managed by the code of std::vector. You do have to mind that doubles and shorts must not be destroyed as long as elements of data still point to them.

like image 135
eerorika Avatar answered Feb 08 '23 17:02

eerorika