首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在流行的实现中,动态内存分配在C和C++中有区别吗?

在流行的实现中,动态内存分配在C和C++中有区别吗?
EN

Stack Overflow用户
提问于 2011-09-16 19:08:48
回答 4查看 4.2K关注 0票数 57

就各自的语言标准而言,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是如何实现的吗?

EN

回答 4

Stack Overflow用户

发布于 2011-09-16 19:15:58

在大多数实现中,operator new()只调用malloc()。事实上,即使是标准的suggests that as a default stratege。当然,如果您想要更好的性能,您可以实现自己的operator new,通常是为一个类实现,但默认情况下通常只是调用malloc()

票数 15
EN

Stack Overflow用户

发布于 2011-09-16 20:56:57

glibc new操作符是malloc的一个薄薄的包装器。glibc malloc对不同大小的分配请求使用不同的策略。您可以查看实现,或者至少可以查看注释here

下面是malloc.c中注释的摘录:

代码语言:javascript
复制
/*
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.
*/
票数 13
EN

Stack Overflow用户

发布于 2011-09-17 00:28:30

在Visual C++上,单步执行new表达式会将我带到new.cpp中的以下代码片段

代码语言:javascript
复制
#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()调用。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7443782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档