I’d like to have an array of pointers to static data. For instance
void func(...) {
...
static int mysize = initial_size;
static double* d[3] = {new double[mysize], new double[mysize], new double[mysize]};
for(int i=0; i < 3; ++i) {
if(cond) {
//-re-allocate d if necessary.
use d here;
}
else {
use d here; //-since d is static; it persists and so this is justified?
}
}
//-Can I get away with not deleting d here??
}
My reasoning is that since d is an array of pointers to static doubles; it is allocated once inside a function and so when everything goes out of scope, it is hopefully deleted? I somehow think not. This is probably wishful thinking and leads to memory leaks?
Perhaps I am better off using a static C++ vector here? I want to use a static here in order to re-use the previously computed and stored data in d, when some conditions are met (e.g. if some condition such as cond or its negation is satisfied). Hope this makes sense and thanks in advance for any ideas.
As @AdamLiss said above, you could leak memory at the re-allocate d if necessary step if you’re not careful to delete the existing arrays before re-allocating:
Even if you remember to delete it like this:
there’s a bug, because the new allocation could throw an exception, leaving
d[0]pointing to deleted memory, but no way to tell that, so when the function next gets called ifd[0]is dereferenced it will be undefined behaviour.This would be OK:
But you would avoid such issues if you used a vector to manage the dynamic memory:
This also has the advantage of being able to query the existing size, via
d[i].size()and not having to manually copy elements from the old array to the new one when reallocating