全局非抛出:: operator new和std :: malloc之间的区别 [英] Difference between global non-throwing ::operator new and 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
,
- 您可以方便地替换
:: operator new
; -
malloc
带有realloc
,而new
没有等效项; -
new
具有new_handler
,没有malloc
- you can portably replace
::operator new
; malloc
comes withrealloc
, for whichnew
has no equivalent;new
has the concept of anew_handler
, for which there is nomalloc
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屋!