MALLOC 和new /delete 区别

      When new has an object, space for the object is not only allocated but the object's constructor is called. And similarly when delete as an object, the object's destructor is called before the memory is released. If malloc and free are used, the destructor and constructor do not get called respectively and obviously, this simply won't do in C++ except in certain very rare situations where classes are present without any specific destructor/constructors.

                      Operator new automatically calculates the size of the object that it constructs. Conversely, with malloc(), the programmer has to specify explicitly the number of bytes that have to be allocated. In addition, malloc() returns void *, which has to be explicitly cast to the desired type. This is both tedious and dangerous. Operator new returns a pointer to the desired type, so no explicit typecast is required.

                       new and delete automatically construct and destroy objects. malloc() and free(), on the other hand, merely allocate and deallocate raw memory from the heap. delete can be overloaded, free cannot. delete invokes the destructor of the object to be deallocated, free does not do this. 

The difference could be qouted as -

1. Operator new constructs an object (calls constructor of object), malloc does not.

2. Operator new is an operator, malloc is a function.

3. Operator new can be overloaded, malloc cannot be overloaded.

4. Operator new throws an exception if there is not enough memory, malloc returns a NULL.

5. Operator new[] requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.               

6. malloc() returns void *, which has to be explicitly cast to the desired type but new returns the proper type.

7. Operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.

8. The new/delete couple does not have a realloc alternative that is available when malloc/free pair is used. realloc is used to resize the length of an array or a memory block dynamically.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值