std::allocator() function in C++
In this tutorial we will study about std::allocator() function in C++.
What is Std allocator?
Allocators are objects which are responsible for encapsulating(enclose (something) in or as if in a capsule) for memory management. The default value of parameters that this function uses delete and new for allocating and removing the space.
Why we are using std allocator?
With the new/delete keywords we cannot write C++ STL vectors as we can’t allocate without initializing and we cannot destroy without deallocating. Also, we cannot use malloc as it is ancient and considered bad practice in C++.
Allocators provide a modern solution!
- Splitting up new and delete
Split new into allocate and construct
Split delete into destroy and deallocate - T* allocate(size_t n)
Allocate memory of size n*sizeof(T) but do not initializes memory. - void construct(Pointer p, Args&&…args)
construct an object instance in place at pointer p, pass args to the constructor. - void destroy(pointer p)
Destroys the object at pointer p(calls the destructor). - void deallocate(pointer p, size_t n)
deallocates block of memory size n*sizeof(T) at pointer p.
Example of std::allocator() function in C++
let’s see an example of this function
// std allocator() function #include <iostream> #include <memory> using namespace std; int main() { allocator<int> myAllocator; // allocate space for five integers int* array = myAllocator.allocate(5); myAllocator.construct(array, 50); array[3] = 60; cout << array[3] << endl; cout << array[0] << endl; // deallocate function myAllocator.deallocate(array, 5); return 0; }
Output
60 50
Where are allocators used?
All STL containers use allocators in one way or another.
- Allow STL containers to work with types that have no default constructors, assignment, operators, copy constructors, etc.
- Node-based containers such as linked list, BST also use allocators for allocating node types.
- allows types like vectors to erase in the middle of an array.
Also read: std::include() function in C++
Leave a Reply