什么是分配器,它们的使用何时需要? [英] What are allocators and when is their use necessary?

查看:207
本文介绍了什么是分配器,它们的使用何时需要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++和标准库上阅读书籍时,我经常看到对分配器的引用。



例如,Nicolai Josuttis的 >在最后一章详细讨论它们,以及Scott Meyers的 Effective STL

中的两个项目10(注意分配器的约定和约束)和11(理解自定义分配器的合法使用



我的问题是,分配器如何代表一个特殊的内存模型?是默认的STL内存管理不够吗?



如果可能,请用简单的内存模型示例解释。



在大多数情况下,默认分配器是完全精确的。但在某些情况下,您可以通过将其替换为其他东西来提高效率。典型的例子是当你需要/想分配大量非常小的对象时。例如,考虑一个字符串的向量,每个字符串可能只有十几个字节左右。正常的分配器使用 operator new ,这可能对这样的小对象施加相当高的开销。创建一个自定义分配器,分配更大的内存块,然后根据需要进行细分,可以节省相当多的内存和时间。


While reading books on C++ and the standard library, I see frequent references to allocators.

For example, Nicolai Josuttis's The C++ Standard Library discusses them in detail in the last chapter, and both items 10 ("be aware of allocators' conventions & restrictions") and 11 ("understand the legitimate uses of custom allocators") in Scott Meyers's Effective STL are about their use.

My question is, how do allocators represent a special memory model? Is the default STL memory management not enough? When should allocators be used instead?

If possible, please explain with a simple memory model example.

解决方案

An allocator abstracts allocating raw memory, and constructing/destroying objects in that memory.

In most cases, the default Allocator is perfectly fine. In some cases, however, you can increase efficiency by replacing it with something else. The classic example is when you need/want to allocate a large number of very small objects. Consider, for example, a vector of strings that might each be only a dozen bytes or so. The normal allocator uses operator new, which might impose pretty high overhead for such small objects. Creating a custom allocator that allocates a larger chunk of memory, then sub-divides it as needed can save quite a bit of both memory and time.

这篇关于什么是分配器,它们的使用何时需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆