How to prevent memory leak in this case?

Apr 5, 2016 at 5:28pm
Assuming I have a class A with construct:
A(int a);


vector<A *> vectorForA;
for(i=0; i<10; i++)
{
vectorForA.push_back(new A(i));
}

later, if I want to change a element in vectorForA, do I need first delete that pointer and put a new one like :
delete vectorForA[3];
vectorForA[3] = new A(10);

And before the program finished, I need to delete all pointers inside it like:
for (std::vector<A*>::iterator it = vectorForA.begin() ; it != vectorForA.end(); ++it)
{
delete *it
}


Correct?

Thank you.
Apr 5, 2016 at 5:39pm
later, if I want to change a element in vectorForA, do I need first delete that pointer and put a new one like :
1
2
delete vectorForA[3];
vectorForA[3] = new A(10);

Whether that's necessary or not depends on code you haven't shown us, but this would work, yes.


And before the program finished, I need to delete all pointers inside it like:

Yes.


Preferably store the object themselves in the vector or smart pointers so such manual memory management isn't necessary.
Apr 6, 2016 at 7:07pm
Thank you, cire.

You mentioned :

Whether that's necessary or not depends on code you haven't shown us, but this would work, yes.


Would you please show me when it is necessary and when it will be unecessary?

Thanks again.
Last edited on Apr 6, 2016 at 7:08pm
Apr 7, 2016 at 1:16pm
Would you please show me when it is necessary and when it will be unecessary?

If, for instance, you have a functional copy or move assignment operator, an explicit new and delete would not be required.

Instead of:
1
2
   delete vectorForA[3];
   vectorForA[3] = new A(10);


You might write:
*vectorForA[3] = A(10);

Apr 14, 2016 at 3:06am
Thank you very much, cire.
Topic archived. No new replies allowed.