Say I have a vector which holds pointers pointing to dynamic memory but also addresses of variables declared on the stack, is there a way to safely loop through and delete only the dynamic memory or am I constrained to just use one or the other? or is doing the following safe? I thought maybe the outcome would be unpredictable depending on the compiler.
std::vector<int*> theInts;
int* i = new int;
*i = 1;
theInts.push_back(i);
int j = 2;
theInts.push_back(&j);
std::vector<int*>::iterator iIt=theInts.begin();
for(;iIt<theInts.end();iIt++)
delete *iIt;
edit:
I’ve temporarily changed things to use raw pointers whilst i look into shared pointers, in the meantime could someone tell me if the following is safe? its a broken down version of what my program is now doing
vector<int*>theInts;
int* anInt = new int;
theInts.push_back(anInt);
if(NULL != anInt)
delete anInt;
anInt = NULL;
vector<int*>::iterator bIt = theInts.begin();
for(;bIt!=theInts.end();bIt++)
{
int* aInt = *bIt;
if(NULL!=aInt)
delete aInt;
aInt=NULL;
}
theInts.clear();
You can only delete a pointer that’s either the result of
newor a null pointer.&jwasn’t the result ofnew, and isn’t a null pointer.So your code isn’t safe. There’s no portable way to find out, just from the pointer, whether it points to an automatic or dynamic object.
You could separately maintain a flag indicating which it is, or you could use
shared_ptrorunique_ptrinstead of raw pointers, and for the stack variables set the deleter to a do-nothing function.