How to prevent memory leak in this case?

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.
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.
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
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);

Thank you very much, cire.
Topic archived. No new replies allowed.