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\n"; } ~Player(){ cout << "call Player::dtor\n"; } void Log(){ cout << "i am player\n"; } }; int main(){ cout << "Initiate by new\n"; Player* p1 = new Player(); p1->Log(); delete p1; cout << "Initiate by malloc\n"; 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
#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 只能分配实例所占内存的整数倍数大小
结论:
学习知识的时候如果能把握整个技术的发展历史和脉络,这样对有些比较难懂的知识就很容易理解了。将这些技术放在其所存在的年代,考虑到当时的软硬件环境,可以更好的理解技术本身。这篇文章是很浅层次的说明了他们的区别,如果有兴趣可以去研究他们的具体实现,能发现更大的乐趣。
原文地址:http://blog.csdn.net/hackmind/article/details/39644055