c++heap-memoryallocatoralloc

What's the advantage of using std::allocator instead of new in C++?


I've just read about std::allocator. In my opinion, it is more complicated to use it instead of using new and delete.

With allocator we must explicitly allocate heap memory, construct it, destroy it, and then finally deallocate the memory. So why was it created?

In which cases can it be used and when should it be used instead of new and delete?


Solution

  • std::allocator is the default memory allocator for the standard library containers, and you can substitute your own allocators. This allows you to control how the standard containers allocate memory. But I don't think that your question is about std::allocator specifically, but rather the strategy of allocating memory, then constucting objects in that memory, rather than using new T[N], for example.

    And the reason for that is that new T[N] doesn't allow you control over what constructors are called. And it forces you to construct all your objects at the same time. This is terrible for the purposes of, for example, std::vector where you only want to allocate occasionally.

    With a raw memory allocator, you can allocate a certain amount of memory, which determines your capacity. Then, as the user adds items to the vector (using the constructor of their choice), you can construct objects in place in this memory.

    Then when you run out of memory, you allocate more, typically twice as much. If std::vector used new T[N], it would have to reallocate every time you wanted to add or remove an element, which would be terrible for performance. You would also be forced to use the default constructor for all the objects, which puts an unnecessary restriction on the types of objects std::vector can hold.