Malloc/New is a library function.
New/delete is an operator.
For non-Internal data objects, using malloc/free alone cannot meet the requirements of dynamic objects. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free. Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory.
C ++ code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
Class OBJ { Public: OBJ (void) {cout <"initialization" <Endl ;} ~ OBJ (void) {cout <"Destroy" <Endl ;} Void initialize (void) {cout <"initialization" <Endl ;} Void destroy (void) {cout <"Destroy" <Endl ;} };
Void usemallocfree (void) { OBJ * A = (OBJ *) malloc (sizeof (OBJ); // allocate memory A-> initialize (); // init //... A-> destroy (); // destroy Free (a); // free memory } Void usenewdelete (void) { OBJ * A = new OBJ; // allocate memory and construct object //... Delete A; // destroy object and free memory }
|
Http://lklkdawei.blog.163.com/blog/static/32574109200881445518891/
Http://www.cnblogs.com/lazycoding/archive/2012/01/02/2310409.html
Malloc/free vs new/delete