C++ Blog

Monday, April 02, 2007

"delete" operator in C++

1) delete calls the destructor for an object before it deallocates the memory.

2) delete should be called for objects that are constructed with new only, if it is used for the object that was allocated with malloc then the result is undefined.

3) delete should be called only for dynamically allocated objects should not be used for the objects in stack if it is used then the result is undefined.

4) Deleting array of objects should be used as delete[] ptr or if it used like delete ptr; it deletes only the first object and the remaining elements are not deallocated.
For example;
student *obj = new student[10];
...
...
...
delete []obj; // This is correct way to delete. delete obj; will result in deleting obj[0] alone.

5) Deleting an object twice using delete is not recommended and the result it un-defined.
For example;
student *obj = new student();
....
delete obj;
....
...
delete obj; // The result is undefined because the previous delete doesn't gurantee storing 0 in the obj.

6) deleting a object pointer with value 0 wont result an error.
For example;
student *obj = new student();
....
delete obj;
obj = 0;
...
delete obj; // This is ok because obj has 0

0 Comments:

Post a Comment

<< Home