Difference between global non-throwing ::operator new and std::malloc(全局非抛出 ::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* operator 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 有什么区别? 因为它谈到使用 global operator new
实际上并不执行任何 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.
推荐答案
除了语法和 free
与 delete
之外,主要区别是
The main differences, aside from syntax and free
vs. delete
, are
- 你可以便携地替换
::operator新的
; 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.
(替换 malloc
会打开一个 蠕虫病毒.它可以完成,但不可移植,因为它需要链接器的知识.)
(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 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:全局非抛出 ::operator new 和 std::malloc 的区别
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01