就各自的语言标准而言,C仅通过malloc()
家族提供动态内存分配,而在C++中,最常见的分配形式是由::operator new()
执行的。C风格的malloc在C++中也可用,许多"baby's first allocator“示例使用它作为其核心分配函数,但我很好奇当代编译器如何实现实际的生成操作符-new。
它只是一个围绕malloc()
的薄薄的包装器,还是由于典型的C++程序与典型的C程序的内存分配行为有很大的不同,它的实现方式有根本的不同?
编辑:我认为主要的区别通常被描述为:C程序有更少、更大、更长的分配,而C++程序有很多、小、短的分配。如果这是错误的,请随时加入,但听起来似乎可以从考虑到这一点中受益。
对于像GCC这样的编译器来说,只有一个核心分配实现并将其用于所有相关语言是很容易的,所以我想知道在每种语言中尝试优化结果分配性能的细节是否存在差异。
更新:感谢所有精彩的答案!在GCC看来,这个问题完全是由ptmalloc解决的,而且MSVC的核心也使用了malloc
。有人知道MSVC-malloc是如何实现的吗?
发布于 2011-09-16 19:15:58
在大多数实现中,operator new()
只调用malloc()
。事实上,即使是标准的suggests that as a default stratege。当然,如果您想要更好的性能,您可以实现自己的operator new
,通常是为一个类实现,但默认情况下通常只是调用malloc()
。
发布于 2011-09-16 20:56:57
glibc new操作符是malloc的一个薄薄的包装器。glibc malloc对不同大小的分配请求使用不同的策略。您可以查看实现,或者至少可以查看注释here。
下面是malloc.c中注释的摘录:
/*
47 This is not the fastest, most space-conserving, most portable, or
48 most tunable malloc ever written. However it is among the fastest
49 while also being among the most space-conserving, portable and tunable.
50 Consistent balance across these factors results in a good general-purpose
51 allocator for malloc-intensive programs.
52
53 The main properties of the algorithms are:
54 * For large (>= 512 bytes) requests, it is a pure best-fit allocator,
55 with ties normally decided via FIFO (i.e. least recently used).
56 * For small (<= 64 bytes by default) requests, it is a caching
57 allocator, that maintains pools of quickly recycled chunks.
58 * In between, and for combinations of large and small requests, it does
59 the best it can trying to meet both goals at once.
60 * For very large requests (>= 128KB by default), it relies on system
61 memory mapping facilities, if supported.
*/
发布于 2011-09-17 00:28:30
在Visual C++上,单步执行new
表达式会将我带到new.cpp
中的以下代码片段
#include <cstdlib>
#include <new>
_C_LIB_DECL
int __cdecl _callnewh(size_t size) _THROW1(_STD bad_alloc);
_END_C_LIB_DECL
void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
{ // try to allocate size bytes
void *p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{ // report no memory
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
所以VC++的new
也包装了malloc()
调用。
https://stackoverflow.com/questions/7443782
复制相似问题