Tuesday, August 24, 2010

new/delete operator

1. Return type of delete operator is void (not void*)




2. Exception and valid cases


char *p;
delete p; ==> exception (shown in picture)




Where as
char *p = 0;
delete p; .==> You can, however, use delete on a pointer with the value 0. This provision means that, when newreturns 0 on failure, deleting the result of a failed new operation is harmless.




2. Mixing both new/malloc and delete/free


class A {
public:
   A() { cout << "Constructor" << endl;
   ~A() { cout << "Destructor" << endl;
};


int main() {
  A *a = new A;
  free(a);                 ==> Calls only constructor; not destructor


 A *b = (A*)malloc(sizeof(A));
 delete b;               ==> Calls only destructor; not constructor


 A *c = new A;
 delete c;                ==> Calls both constructor and destructor
}                          



No comments:

Post a Comment