首页投稿(暂停使用,暂停投稿)程序员

malloc/free & new/delete的区别

2016-04-01  本文已影响304人  AwesomeAshe

上一篇文章学习了free,那么问题来了,c++里面的new/delete似乎也是这个功能啊,所以区别是什么呢?

于是在stackoverflow上搜了一下:
malloc/free & new/delete的区别

搬运工来了。。:

Allocate/release memory
1,Memory allocated from 'Free Store'
2,Returns a fully typed pointer.
3,new (standard version) never returns a NULL (will throw on failure)
4,Are called with Type-ID (compiler calculates the size)
5,Has a version explicitly to handle arrays.
6,Reallocating (to get more space) not handled intuitively (because of copy constructor).
7,Whether they call malloc/free is implementation defined.
8,Can add a new memory allocator to deal with low memory (set_new_handler)
9,operator new/delete can be overridden legally
10,constructor/destructor used to initialize/destroy the object

malloc/free
Allocates/release memory
1,Memory allocated from 'Heap'
2,Returns a void*
3,Returns NULL on failure
4,Must specify the size required in bytes.
5,Allocating array requires manual calculation of space.
6,Reallocating larger chunk of memory simple (No copy constructor to worry about)
7,They will NOT call new/delete.
8,No way to splice user code into the allocation sequence to help with low memory.
9,malloc/free can NOT be overridden legally

继续补充在网上看到的:

malloc与free是C++/C 语言的标准库函数,new/delete 是C++的运算符。对于非内部数据类的对象而言,光用maloc/free 无法满足动态对象的要求。对象在创建的同时要自动执行构造函数, 对象消亡之前要自动执行析构函数。由于malloc/free 是库函数而不是运算符,不在编译器控制权限之内,不能够把执行构造函数和析构函数的任务强加malloc/free。

这个很重要,new的是对象!

上一篇 下一篇

猜你喜欢

热点阅读