I have a small question:
Foo *myFoo;
myFoo = new Foo(anotherFoo); // some deep copy of another object
myFoo = new Foo(yetAnotherFoo); // another deep copy of yet another object
Is this a memory leak and if yes, how can I avoid it properly? The situation in my program is, that ‘myFoo’ is a class member and I want to use it as a “one and only” storage-object for a deep copy of some other object from time to time (because the copied object is modified afterwards and I need the initial object for later comparison).
I have tried a simple workaround like:
// within a class method of the same class
if (myFoo!=NULL) delete myFoo;
myFoo = new Foo(fooToStore);
but this crashes my program as soon as the destructor is called. I am not sure if my (non-trivial) destructor is a bit buggy (different problem not to discuss here) or if deleting a class-member object via delete within a class method is forbidden in general.
Thanks a lot for your time and help – appreciate it!
Mark
Yes, it is a memory leak, because the second assignment to
myFoocauses the firstFooyou allocated to become inaccessible. DeletingmyFoobetween successive allocations is the correct thing to do. Note that you don’t need to check for a null pointer:deletetakes care of that. It looks very likely that you have some problem inFoo‘s destructor.