How to Create Custom Memory Allocator in C++?
Last Updated :
01 Mar, 2024
In C++ containers, memory allocation is generally managed by allocators through new and delete operators or malloc() and free() functions but for custom memory management we can use the custom allocators. In this article, we will learn how can one create a custom memory allocator in C++.
Custom Memory Allocator in C++
In C++, we can use a custom memory allocator to control how memory is allocated and deallocated for the containers by implementing our own functions for allocating and freeing memory. We must define the following in our allocators
- A type
value_type
.
- The allocation function to allocate memory for
n
objects.
- The deallocation function to deallocate memory for
n
objects pointed to by p
.
Note: To know about the conventions of allocator names and minimum requirements, read about allocator_traits in C++.
C++ Program to Use Custom Memory Allocator
The below example demonstrates how we can use a custom memory allocator in C++.
C++
#include <iostream>
#include <vector>
using namespace std;
template < typename T> class myClass {
public :
typedef T value_type;
myClass() noexcept {}
T* allocate(std:: size_t n)
{
return static_cast <T*>(
::operator new (n * sizeof (T)));
}
void deallocate(T* p, std:: size_t n) noexcept
{
::operator delete (p);
}
};
int main()
{
vector< int , myClass< int > > vec;
for ( int i = 1; i <= 5; ++i) {
vec.push_back(i);
}
for ( const auto & elem : vec) {
cout << elem << " " ;
}
cout << endl;
return 0;
}
|
Explanation: In the above example we defined a custom memory allocator class myClass that provides allocate() and deallocate() functions to allocate memory for the n objects of type T using new operator and deallocate memory using delete operator and in the main() function a std::vector is declared with custom allocator myClass<int> so when elements are added to vector custom allocator is used to the allocate memory for them and finally, print the elements of vector.
Share your thoughts in the comments
Please Login to comment...