Safe removal of the array - delete[]

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
In constructor i must write:

 
arr = NULL;


;-)
closed account (S6k9GNh0)
Um, wut? I'm pretty sure thats not what you do and is a large source of memory leaks...
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.
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)
    {
    }
};
closed account (S6k9GNh0)
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.