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.



Previous Article
Next Article

Similar Reads

Why Linked List is implemented on Heap memory rather than Stack memory?
Pre-requisite: Linked List Data StructureStack vsHeap Memory Allocation The Linked List is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers. It is implemented on the heap memory rather than the stack memory. This article discusses the reason behind
14 min read
How To Create Custom Arduino Library Using C++
What is the Arduino library? Libraries are a collection of precompiled, reusable code or routines which are used by developers to reduce the development time. Arduino libraries are written in C or C++. These libraries provide us with a convenient way to share code. Arduino IDE already consists of a set of standard libraries, one can use these libra
6 min read
Program to create Custom Vector Class in C++
The task is to implement a custom vector class similar to the STL vector with following functions: int push_back(data): adds an element(of any data_type) to the end of array and also returns the number of elements in that vectordata_type pop_back(): removes an element from the end of array, also returns the popped elementint size() const: returns t
5 min read
How to create a custom String class in C++ with basic functionalities
In this article, we will create our custom string class which will have the same functionality as the existing string class.The string class has the following basic functionalities: Constructor with no arguments: This allocates the storage for the string object in the heap and assign the value as a NULL character.Constructor with only one argument
8 min read
How to Create Custom Assignment Operator in C++?
In C++, operator overloading allows us to redefine the behavior of an operator for a class. In this article, we will learn how to create a custom assignment operator for a class in C++. Creating Custom Assignment (=) Operator in C++To create a custom assignment operator, we need to define an overloaded assignment operator function in our class. The
2 min read
How to Create std::vector of Custom Classes or Structs in C++?
In C++, std::vectors are dynamic arrays that can resize themselves during the runtime, and classes or structs allow the users to create custom data types of their choice. There might be many situations when we want to store a custom data type into a vector. In this article, we will learn how to create a vector of custom classes or structs in C++. E
3 min read
How to create an Array of Objects in the Stack memory?
What is an Array of Objects? An array of objects is a data structure that stores a collection of objects of the same type. The objects in the array are stored in contiguous memory locations, and the array provides indexed access to the objects. This means that you can access an individual object in the array using its index, just like you would wit
6 min read
User-defined Custom Exception with class in C++
We can use Exception handling with class too. Even we can throw an exception of user defined class types. For throwing an exception of say demo class type within try block we may write throw demo(); Example 1: Program to implement exception handling with single class C/C++ Code #include &lt;iostream&gt; using namespace std; class demo { }; int main
3 min read
How to Initialize Multiset with Custom Comparator in C++?
In C++, a multiset container stores the data in a sorted order. By default, this order is increasing order (using &lt; operator as comparator) but we can change this order by providing a custom comparator. In this article, we will learn how to initialize a multiset with a custom comparator function in C++. For Example, Input: 1 8 6 4 9 3 2 5 7 Outp
2 min read
How to Throw a Custom Exception in C++?
In C++, exception handling is done by throwing an exception in a try block and catching it in the catch block. We generally throw the built-in exceptions provided in the &lt;exception&gt; header but we can also create our own custom exceptions. In this article, we will discuss how to throw a custom exception in C++. Throwing Custom Exceptions in C+
2 min read