gpt4 book ai didi

c++ - 在流行的实现中,C 和 C++ 中的动态内存分配是否不同?

转载 作者:IT老高 更新时间:2023-10-28 13:23:40 26 4
gpt4 key购买 nike

就各自的语言标准而言,C 仅通过 malloc() 提供动态内存分配。家族,而在 C++ 中,最常见的分配形式是由 ::operator new() 执行的。 . C 风格的 malloc 也可以在 C++ 中使用,许多“婴儿的第一个分配器”示例都使用它作为其核心分配功能,但我很好奇当代编译器如何实现实际的生产 operator-new。

它只是malloc() 周围的薄包装吗? ,还是由于典型 C++ 程序与典型 C 程序相比内存分配行为截然不同,它的实现方式根本不同?

[编辑: 我相信主要区别通常描述如下:C 程序具有较少、较大、长期存在的分配,而 C++ 程序具有许多、较小、短期的分配。如果有误,请随时提出意见,但听起来考虑到这一点会受益。]

对于像 GCC 这样的编译器,只有一个核心分配实现并将其用于所有相关语言是很容易的,所以我想知道在尝试优化每种语言的最终分配性能的细节上是否存在差异。


更新:感谢所有精彩的回答!在 GCC 中,这似乎完全由 ptmalloc 解决,并且 MSVC 也使用 malloc在核心。有谁知道 MSVC-malloc 是如何实现的?

最佳答案

这里是g++ 4.6.1使用的实现:

_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) throw (std::bad_alloc)
{
void *p;

/* malloc (0) is unpredictable; avoid it. */
if (sz == 0)
sz = 1;
p = (void *) malloc (sz);
while (p == 0)
{
new_handler handler = __new_handler;
if (! handler)
#ifdef __EXCEPTIONS
throw bad_alloc();
#else
std::abort();
#endif
handler ();
p = (void *) malloc (sz);
}

return p;
}

这可以在 g++ 源代码发行版中的 libstdc++-v3/libsupc++/new_op.cc 中找到。

如您所见,它是一个相当薄的 malloc 包装器。

edit 在许多系统上,可以微调 malloc 的行为,通常是通过调用 mallopt 或设置环境变量。这是一个article讨论 Linux 上可用的一些功能。

According to Wikipedia , glibc 版本 2.3+ 使用分配器的修改版本,称为 ptmalloc ,它本身是由 Doug Lea 设计的 dlmalloc 的派生词.有趣的是,在 article about dlmalloc Doug Lea 给出了以下观点(强调我的观点):

I wrote the first version of the allocator after writing some C++ programs that almost exclusively relied on allocating dynamic memory. I found that they ran much more slowly and/or with much more total memory consumption than I expected them to. This was due to characteristics of the memory allocators on the systems I was running on (mainly the then-current versions of SunOs and BSD ). To counter this, at first I wrote a number of special-purpose allocators in C++, normally by overloading operator new for various classes. Some of these are described in a paper on C++ allocation techniques that was adapted into the 1989 C++ Report article Some storage allocation techniques for container classes.

However, I soon realized that building a special allocator for each new class that tended to be dynamically allocated and heavily used was not a good strategy when building kinds of general-purpose programming support classes I was writing at the time. (From 1986 to 1991, I was the the primary author of libg++ , the GNU C++ library.) A broader solution was needed -- to write an allocator that was good enough under normal C++ and C loads so that programmers would not be tempted to write special-purpose allocators except under very special conditions.

This article presents a description of some of the main design goals, algorithms, and implementation considerations for this allocator.

关于c++ - 在流行的实现中,C 和 C++ 中的动态内存分配是否不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7443782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com