Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between memory allocation through new and allocator

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?

like image 799
BJC Avatar asked Oct 22 '22 17:10

BJC


1 Answers

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 allocators, 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 allocators.

like image 162
phoeagon Avatar answered Oct 24 '22 09:10

phoeagon