Open In App

How to Create Custom Memory Allocator in C++?

Last Updated : 01 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to show how to create custom allocator
#include <iostream>
#include <vector>
using namespace std;
  
// Custom memory allocator class
template <typename T> class myClass {
public:
    typedef T value_type;
    // Constructor
    myClass() noexcept {}
    // Allocate memory for n objects of type T
    T* allocate(std::size_t n)
    {
        return static_cast<T*>(
            ::operator new(n * sizeof(T)));
    }
    // Deallocate memory
    void deallocate(T* p, std::size_t n) noexcept
    {
        ::operator delete(p);
    }
};
int main()
{
    // Define a vector with the custom allocator
    vector<int, myClass<int> > vec;
    for (int i = 1; i <= 5; ++i) {
        vec.push_back(i);
    }
    // Print the elements
    for (const auto& elem : vec) {
        cout << elem << " ";
    }
    cout << endl;
    return 0;
}


Output

1 2 3 4 5 

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads