问题
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