Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Callling object constructor/destructor with a custom allocator

I have been looking into custom allocators and I quite often see them using some kind of function to allocate memory. For testing purposes and further educate my self, I tried to make a "simple" example of doing so. However, there is one fundamental thing I am understand on how to do. One of the key differences in malloc vs new is that with new the constructor is called. What if I wanted to write my own allocator that was essentially replacing new, how would I get the constructor to be called when using malloc?

I understand that on classes I can overload new and delete for the class, so I suppose a big part of the question is, how is new calling the objects constructor during allocation? Similarly, I am interested in how delete is calling the destructor.

I created a sample test code that I was hoping to have the SomeClass constructor called during allocation, but I don't see how.

#include <malloc.h>

void* SomeAllocationFunction(size_t size) {
    return malloc(size);
}

class SomeClass
{
public:
    SomeClass() {
        int con = 1000;
    }

    ~SomeClass() {
        int des = 80;
    }
};

int main(void){
    SomeClass* t = (SomeClass*)SomeAllocationFunction(sizeof(SomeClass));
    return 0;
}

(As a note, I know I can just use new. However, for the purposes of learning I am trying to create a custom allocator that does not just call new or placement new).

like image 931
mmurphy Avatar asked Apr 18 '12 00:04

mmurphy


1 Answers

With a placement new you can pass an already allocated memory location to the new operator. Then new will construct the object at the given place without doing an allocation on itself.

Edit:

This is how it could be implemented:

int main(void){
    // get memory
    void * mem_t = SomeAllocationFunction(sizeof(SomeClass));
    // construct instance
    SomeClass* t = new(mem_t) SomeClass;

    // more code

    // clean up instance
    t->~SomeClass();
    return 0;
}
like image 122
bjhend Avatar answered Oct 20 '22 00:10

bjhend