quote:Original post by civguy{ int* x = new int[10]; ... delete[] x; x = 0;}
What does x=0 help here? The variable x ceases to exist right after the assignment, so the assignment x=0 was meaningless.
No it doesn't. The *memory pointed to by x* is freed (the data doesn't even cease to exist! It's still there - though probably unreachable - until something overwrites it). The pointer is - apparently - left dangling.
Try:
{ int* x = new int[10]; ... delete[] x; delete[] x;}
If I remember c++ worth a damn, the second delete[] will crash, because x is still pointing at the location where the int[] was, but the memory has already been freed.
Try:
{ int * x = new int[10]; ... delete[] x; x = NULL; delete[] x;}
Now it works, because deleting NULL is ok (as a special case).
What's happening to the OP, according to the theory people are proposing, is that multiple instances of the object have their own variable explode, but each has the same value in that variable - the address of a *shared* part2[] array - because copying/assignment is shallow by default. So, when the destructor is called for each object:
- When the first is destroyed, the memory of the part2[] array gets deleted. The value of 'explode' in the other objects is not touched, and thus still points at that memory.
- When the second is destroyed, the code tries to free the memory again, and crashes and burns.
You're right insofar as assigning NULL to 'explode' can't help matters. But I felt the need to be pedantic. If it were possible in the destructor to find every other instance of the object and set their 'explode' pointers to NULL, then things would work out ok.
So the question becomes how the part2[] array *should* be handled. There are a couple of possibilities:
- you might really want a separate copy of it for every instance of the object, so they can't write over each other's data. In that case, you need to implement (and make public) a copy constructor and an assignment operator (i.e. overload 'operator='), which clones the part2[] array and sets explode to point at the clone.
- you might want to share the data, either to save memory on constant data, or because collaboratively writing the data is the whole point of the objects. In that case you can:
- make part2[] a static member of the class.
- wrap part2[] in a class and reference-count it; in the X constructor/destructor you send addUser/removeUser() messages to a Part2ArrayWrapper instance, and when the count reaches 0, the Part2ArrayWrapper delete[]s the part2[]. deleting the Part2ArrayWrapper itself is an exercise for the reader.
- Use a garbage-collected language like Java and save yourself at least part of the trouble.
[edited by - Zahlman on January 11, 2004 9:08:28 PM]