全局运算符new和malloc之间的差异 [英] Difference between global operator new and malloc

查看:157
本文介绍了全局运算符new和malloc之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++有几个函数来获取动态存储,其中大多数在一些基本方面有所不同。通常由操作系统添加几个。

C++ has several functions to acquire dynamic storage, most of which differ in some fundamental way. Several more are usually added by the OS.

其中两个由于其可移植性和相似性而特别感兴趣: malloc :: operator new

Two of these are of special interest due to their portability and similarity: malloc and ::operator new.

全局 void * operator new(size_t,:: std :: nothrow&)和 void * malloc(size_t)

由于我所说的似乎有些混乱,请考虑以下两个调用:

Since there seems to be some confusion what I am talking about, consider the following two calls:

void* p = ::std::malloc(10);
void* q = ::operator new(10, ::std::nothrow);

显而易见的和微不足道的区别是如何释放内存:

The obvious and trivial difference is how to deallocate the memory:

::std::free(p);
::operator delete(q);

注意:此问题不是 new / delete和malloc / free之间的区别是什么?,因为它谈到使用全局 运算符新,实际上不执行任何ctor调用。

Note: This question is not a duplicate of e.g. What is the difference between new/delete and malloc/free? since it talks about using the global operator new that does not actually perform any ctor calls.

推荐答案

除了语法和自由 / code>,

The main differences, aside from syntax and free vs. delete, are


  1. 您可以轻松地 replace :: operator new ;

  2. malloc 附带 realloc ,其中没有等效项;

  3. new 的概念是 new_handler ,因为没有等于malloc

  1. you can portably replace ::operator new;
  2. malloc comes with realloc, for which new has no equivalent;
  3. new has the concept of a new_handler, for which there is no malloc equivalent.

(替换 malloc 打开蠕虫病毒。它可以做,但不可移植,因为它需要链接器的知识。)

(Replacing malloc opens up a can of worms. It can be done, but not portably, because it requires knowledge of the linker.)

这篇关于全局运算符new和malloc之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆