全局非抛出:: operator new和std :: malloc之间的区别 [英] Difference between global non-throwing ::operator new and std::malloc

查看:153
本文介绍了全局非抛出:: operator new和std :: 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 *运算符new(size_t,:: std :: nothrow&) void * malloc(size_t)

Are there any differences (w.r.t. the standard and implementation) between the global void* operator new(size_t, ::std::nothrow&) and 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调用的 global operator new

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.

推荐答案

除语法和 free delete


  1. 您可以方便地替换 :: operator new ;

  2. malloc 带有 realloc ,而 new 没有等效项;

  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.

(替换 m alloc 打开可以蠕虫。可以做到,但不能移植,因为它需要链接程序的知识。)

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

这篇关于全局非抛出:: operator new和std :: malloc之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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