What is the difference between memory allocation through new
/malloc
and allocator
?
Why would we ever need a separate memory allocator for vector if we have the options of new
and malloc
?
What is the difference between memory allocation through new
/malloc
and allocator
?
Why would we ever need a separate memory allocator for vector if we have the options of new
and malloc
?
Eh, I think that new
and malloc
are different and allocator
provides different functions. malloc
returns non-initialized data, and calloc
returns zero-ed data. But new
would call the constructor if you are creating an instance of some class ( not int
, bool
these primitive types, which, by the way, can be initialized as well ). delete
would call the destructor, while free
doesn't.
As for allocator
, it provides a layer of abstraction for the user. allocator
can return constructed object, non-initialized memory space, or destroy a object or release the space. STL containers use allocator
to get memory space and create object.
But note that as custom allocator
is possible, an allocator
does not necessarily manage memory like new
/delete
. It can create a large chunk of memory then do some allocation cache. It can return memory address in areas mapped to files on disk so that the internal data goes into the filesystem as it's modified by the upper layer, container. Also it can call new
to get memory. In this way, allocator
enables user to build containers that lie in specific areas of the memory. So, with allocator
s, the internal logic of containers are separated from the way memory storage is managed.
Actually you can write a class derived from std::allocator
to implement every feature mentioned above.
you might want to read this for a more detailed discussion on allocator
s.
When you use new or malloc, the memory management is hard-wired to the corresponding functions in the runtime of your compiler. In contrast, when an allocator is used, memory management is delegated to the allocator, which is exchangeable. This allows you to alter the memory managing functions used.
There are some good reasons to have this extra level of abstraction and control. For example see: Compelling examples of custom C++ STL allocators?.
In the allocator
class there is an allocate()
which takes two parameters as follows:
pointer allocate (size_type n, allocator<void>::const_pointer hint=0);
According to the reference of allocate() the hint parameter can be used to improve performance by mentioning that you need to allocate a new block of memory adjacent to the one specified. So i believe using the hint you can assign blocks such that they are sequential like in case of an array.
An allocator is a memory manager. STL containers for instance, provide default allocators, but one can customize them as explain in this article (a tutorial for STL allocators): http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c4079/Allocators-STL.htm.