Custom allocator method is not called

I am trying to learn and write a self custom allocator - I was expecting that the cout statement in MyAllocator allocate method should be printed but it never does - what is the wrong am I doing - how to write custom allocator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>

template < class T >
class MyAllocator : public std::allocator<T> {
public:
    T* allocate(size_t size)
    {
        std::cout << "Allocation request size " << size << std::endl;
        return new T[size];
    }

};

int main()
{
    std::vector <int, MyAllocator<int>> x;
    x.push_back(10);
    x.push_back(10);
    x.push_back(10);

    for (auto& var : x)
        std::cout << "Value " << var << std::endl;

}

Output

1
2
3
Value 10
Value 10
Value 10
Last edited on
I'm by no means an expert on writing allocators but implementing rebind seems to fix the issue.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <class T>
class MyAllocator : public std::allocator<T>
{
public:
	T* allocate(size_t size)
	{
		std::cout << "Allocation request size " << size << std::endl;
		return new T[size];
	}
	
	template <class U> 
	struct rebind
	{
		using other = MyAllocator<U>; 
	};
};


Note that allocate is only supposed to allocate memory without actually constructing the objects.
Last edited on
Topic archived. No new replies allowed.