Hi,
I have this following code snippet. I need help in determining what is the right place to call delete and why?
1 2 3 4 5
MyClass1 tMyClass1;
for (int i = 0; i < 11; i++) {
MyClass2 tMyClass2 = new MyClass2(i);
tMyClass1.add(tMyClass2)
}
Should i call "delete tMyClass2"
1. In for loop after the call to add()
or
2. In the add(MyClass2*) method which does it regular logic and then deletes it input parameter which would be tMyClass2.
Did you actually test this anywhere?
tMyClass2 should be a MyClass2* (pointer), because that's what new will return.
Then, the element (on the heap) is added to tMyClass1 (by pointer), which means that deleting it now would cause tMyClass1 to contain deleted data (pointers that point to memory that no longer belongs to them = dangerous!).
Instead, the delete should be in a function of myClass1, when it removes items, or is destroyed itself.
Thanks, my actual code does have MyClass2* tMyClass2 = new MyClass2(i);
I may have rushed it here by typing it on the fly. So, if i understand this right, it should be deleted in the add() method of MyClass1, right?
The answer depends what tMyClass1 is doing with the object internally. If MyClass1 is finished with the object (instead of storing it away) once your add() function is finished, then there's no point in creating it with new in the first place.
If MyClass1 is storing all of your objects somewhere for later use, then deleting it after you've added it will leave tMyClass1 with a dangling pointer. (If this is the case, then you should make sure MyClass1 knows how to clean-up after itself in its destructor, and make sure it either prevents copying or handles copying correctly by doing something with the Copy Constructor and assignment operator)
Thanks Gaminic and Bench82 - MyClass1 is storing it for later use. I will delete the pointers in the destructor of MyClass1 - thanks again for prompt help