Stack-buffer based STL allocator
It is absolutely possible to develop a stack allocator that completely complies with C++11 and C++14. However, you must take into account some of the implications of stack allocation’s implementation, semantics, and interactions with common containers.
Here is a fully compliant stack allocator for C++11 and C++14:-
Stack buffer: When information written to a memory location exceeds the size of that data, a buffer overflow occurs. This can cause program crashes, data corruption, or malicious code to run on your computer.
Approach: The main idea is to
Initially draw memory from a user-supplied fixed-size buffer. Then this allocator will switch to a backup allocator (by default, the std::allocator<T>) when it runs out of room.
- A straightforward approach is to use a stack pointer for allocations and deallocation of memory.
- Increment the stack pointer while allocating and decrease it while deallocating.
This method restricts greatly how you can use the allocator. If used appropriately, it will work properly for something which allocates continuous memory blocks (like vector) but not for something that allocates and deallocates in varying order (like a map).
Allocator in C++: Allocator is a kind of object which is responsible for encapsulating memory management. All containers in the Standard Template Library (STL) have a type parameter Allocator that is defaulted to std::allocator. The default allocator uses operators new and delete to obtain and release memory, respectively.
Declaration of Template: template <class X> class allocator
Things that needs to be considered:
You should think about your allocation habits before using a stack allocator. First, you must think carefully about what it means to allocate and deallocate memory while utilizing a memory buffer on the stack.