Thursday, February 18, 2016

[C++] new/delete, malloc/free, delete[]

1 new/delete  V.S. malloc/free

new will call the constructor and create object in memory (like malloc)
delete will call the destructor (~ClassName() ) and release the memory (like free)

free/malloc are the std library function in C/C++ otherwise new/delete are the operators of C++

why do we need new and delete in C++ :

in C++, when we need to create an object :
     1  reserve a space in the memory  2 execute the constructor
when we need to destroy an object :
     1  execute the destructor    2 release the memory of this object
malloc and free are std library functions and they are not in the control of compiler, so we cannot let them to call the constructor and destructo, thus we need new and delete to do this.


2 delete V.S. delete[]

delete will call the destructor once, but delete[] will call the destructor of every member :
when delete works on an array[], it will call the destructor of every member and than release the memory.
All you should remember is : use new with delete, use new[] with delete[]
ex :
MemTest *mTest1=new MemTest[10];
MemTest *mTest2=new MemTest;
Int *pInt1=new int [10];
Int *pInt2=new int;
delete[]pInt1; //-1-
delete[]pInt2; //-2-
 --> in this case, pInt2 can be a single int or can be an array with only one int, so delete and delete[] both work : for simple type pointer, delete and delete[] are the same, but for user defined complex type pointer , delete and delete[] are different.
delete[]mTest1;//-3-
delete[]mTest2;//-4- --> error : mTest2 is not an array, it's just a pointer

No comments:

Post a Comment