How does an allocator create and destroy and array, for example
int* someInt = someAllocator(3);
Where without the allocator it would just be
int* someInt = new int[3];
Where the allocator is responsible for create each element and ensuring the constructor will be called.
How is the internals for an allocator written without the use of new? Could someone provide and example of the function?
I do not want to just use std::vector as I am trying to learn how an allocator will create an array.
The problem of general memory allocation is a surprisingly tricky one. Some consider it solved and some unsolvable 😉 If you are interested in internals, start by taking a look at Doug Lea’s malloc.
The specialized memory allocators are typically much simpler – they trade the generality (e.g. by making the size fixed) for simplicity and performance. Be careful though, using general memory allocation is usually better than a hodge-podge of special allocators in realistic programs.
Once a block of memory is allocated through the “magic” of the memory allocator, it can be initialized at container’s pleasure using placement new.
— EDIT —
The placement new is not useful for “normal” programming – you’d only need it when implementing your own container to separate memory allocation from object construction. That being said, here is a slightly contrived example for using placement new:
This prints:
— EDIT 2 —
OK, here is how you do it for the array:
BTW, if
Ahad a default constructor, you could try call it on all elements like this……but this would open a can of worms you really wouldn’t want to deal with.