假设我有 10 kB 的堆并混合使用 C 和 C++ 代码。
char* block1 = malloc(5*1024); //allocate 5
char* block2 = new[](4*1024); // allocate 4
是否存在 C 堆和 C++ 堆,或者两者共用一个堆?这样“new”就知道堆的前 5 kb 已经分配了吗?
最佳答案
可能有也可能没有单独的 C 和 C++ 堆。您无法编写可以区分差异的符合标准的 C++ 程序,因此这完全取决于实现。
该标准描述了 operator new
默认行为的第一步,如下所示:
Executes a loop: Within the loop, the function first attempts to allocate the requested storage. Whether the attempt involves a call to the C standard library functions malloc or aligned_alloc is unspecified. [new.delete.single]/4.1.
对于 malloc
本身,标准说:“[aligned_alloc
、calloc
、malloc
和 realloc
] 不要尝试通过调用 ::operator new()
"[c.malloc]/3 来分配存储。
所以意图是可以从operator new
调用malloc
,但这不是必需的。
在实践中,operator new
调用malloc
。
关于c++ - malloc 和 new 是否相互了解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57776731/