Re: Question about destructors
On Feb 7, 11:38 am, "Asger Joergensen" <J...@Asger-P.dk> wrote:
Hi Gus
Gus Gassmann wrote:
I have been working with C++ for about four years now, mostly self-
taught, and I get along reasonably well. However, last week I detected
a memory leak in some code, and trying to locate it I realized that I
do not know enough about destructors. I have created a number of use
cases. How can I make sure in each case that the memory gets destroyed
properly?
Freds solution is the best because it is exception safe, but the
golden rule is:
when ever You use the keyword new it should be matched with the
keyword delete
and when You use new [] it should be matched with delete[]
1. int *x[10];
nothing.
2. int *y = new int[10];
delete[] y;
3. Object *obj = new Object();
delete obj;
etc.
But again Freds solution is better, because the vector takes care of the
deletion when the vector runs out of scoop, even if there is an exception=
..
Some of the code is not written by me, so I am afraid Fred`s solution
does not work. Let me then summarize, just to be absolutely clear:
4. Object **obj = new Object[n];
for (int i=0; i<n; i++) obj[i] = new Object();
for (int i=0; i<n; i++) delete obj[i];
delete[] obj;
5. Object *obj = new Object();
obj->intArray = new int[10];
delete[] obj->intArray;
delete obj;
6. Object **obj = new Object[n];
for (int i=0; i<n; i++) {
obj[i] = new Object();
obj[i]->intArray = new int[10];
}
for (int i=0; i<n; i++) {
delete[] obj[i]->intArray;
delete obj[i];
}
delete[] obj;
Will that do it? Thanks!