new/delete 与 malloc/free的六大区别
1、malloc/free既能够用于C也能够用于C++,但new/delete只能用于C++
2、new能够自动计算需要分配的空间,而malloc需要手动计算字节数,比如:int * p1 = new int[2]; int * p2 = malloc(2*sizeof(int));
3、new/delete直接带具体类型的指针,malloc/free则返回void类型的指针
4、new是类型安全的,malloc则不是,所以int * p = new float[2]会报错,而int * p = malloc(2*sizeof(int))则不会
5、new/delete能够自动调用构造函数和析构函数,而malloc/free则不能。
6、malloc/free需要stdlib.h支持,而new/delete则不需要库文件支持。

浙公网安备 33010602011771号