Safe removal of the array - delete[]
May 10, 2010 at 4:10pm UTC
Hello.
I have problem. I write class witch array int.
I must check that array exist, because i must delete it.
1 2 3 4 5 6 7 8 9 10 11 12
// if i use it first time - array not exist i have error
void deleteArr(){
if (arr != NULL)
delete [] arr;
}
void setArr(){
deleteArr();
int * arr = new int [5];
}
Last edited on May 10, 2010 at 4:14pm UTC
May 10, 2010 at 4:15pm UTC
In constructor i must write:
;-)
May 10, 2010 at 4:17pm UTC
Um, wut? I'm pretty sure thats not what you do and is a large source of memory leaks...
May 10, 2010 at 4:38pm UTC
1 2 3 4
void deleteArr(){
if (arr != NULL)
delete [] arr;
}
the if statement is not necessary. If arr is set to 0 then delete[] will simply ignore it:
1 2 3
void deleteArr(){
delete [] arr;
}
That does the same thing.
May 10, 2010 at 4:42pm UTC
arr = NULL;
I believe in C++ its considered better to use 0 rather than NULL:
arr = 0;
In a constructor, this should be done in the 'initializer list':
1 2 3 4 5 6 7 8
class Test
{
int * arr;
public :
Test() : arr(0)
{
}
};
May 10, 2010 at 5:20pm UTC
Its the same exact thing. It doesn't matter.
And I was under the impression that you were for some reason assigning a data address and then assigning NULL. Not sure why I thought that.
Topic archived. No new replies allowed.