一、new是操作符,而malloc是函数
void* malloc(size_t); void free(void*);
void *operator new (size_t); void operator delete (void *); void *operator new[] (size_t); void operator delete[] (void *);
二、new在调用的时候先分配内存,在调用构造函数,释放的时候调用析构函数。
#include <iostream> using namespace std; class Player{ public: Player(){ cout << "call Player::ctor "; } ~Player(){ cout << "call Player::dtor "; } void Log(){ cout << "i am player "; } }; int main(){ cout << "Initiate by new "; Player* p1 = new Player(); p1->Log(); delete p1; cout << "Initiate by malloc "; Player* p2 = (Player*)malloc(sizeof(Player)); p2->Log(); free(p2); }
输出结果为:
Initiate by new
call Player::ctor
i am player
call Player::dtor
Initiate by malloc
i am player
三、new是类型安全的,malloc返回void*
四、new可以被重载
五、new分配内存更直接和安全
六、malloc 可以被realloc
#include <iostream> using namespace std; int main(){ char* str = (char*)malloc(sizeof(char*) * 6); strcpy(str, "hello"); cout << str << endl; str = (char*)realloc(str, sizeof(char*) * 12); strcat(str, ",world"); cout << str << endl; free(str); }
输出结果为:
hello
hello,world
七、new发生错误抛出异常,malloc返回null
八、malloc可以分配任意字节,new 只能分配实例所占内存的整数倍数大小