Defining my own heap isn't working - is my signature correct?

Hi,

I am defining my own heap like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class MyHeap
{
public:
	void* allocate(size_t size)
	{
		return malloc(size);
	}
	void deallocate(void* p)
	{
		free(p);
	}
	void* operator new(size_t size, MyHeap* heap)
	{
		return heap->allocate(size);
	}
};


I call operator new overload like so:

1
2
3
MyHeap heap;

auto x = new (&heap) int(0);


But MyHeap operator new is never called!!!

What's wrong?


Last edited on
It does not work this way. You use the placement new. The first parameter to that new is the a pointer to the memory location where the object is stored. There will be no further memory allocation, but the constructor of the object will be called. Thus the content of heap will be overwritten with 0.

This

auto x = new (&heap) int(0);

might cause undefined behavior if there is not enough memory reserved on the stack for the int.
ok, how can I make it work? which overload of operator new can I use?
How an I define my own heap?
Last edited on
When you want it for any object created with new you can overload the global new/delete operator. Making MyHeap a singleton:
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
26
27
28
29
30
31
32
33
34
35
class MyHeap
{
public:
	void* allocate(size_t size)
	{
		return malloc(size);
	}
	void deallocate(void* p)
	{
		free(p);
	}

	static MyHeap& instance()
	{
		static MyHeap result;
		return result;
	}
};

void* operator new (std::size_t size)
{
    return MyHeap::instance().allocate(size);
}

void operator delete (void* ptr) noexcept
{
  MyHeap::instance().deallocate(size);
}

int main()
{
  int *i = new int{1};
  delete i;
  return 0;
}
Thanks!

Topic archived. No new replies allowed.