What are allocators and when is their use necessary? [closed]

为君一笑 提交于 2019-12-30 08:12:33

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17848186/what-are-allocators-and-when-is-their-use-necessary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!