Callling object constructor/destructor with a custom allocator

后端 未结 3 1639
一个人的身影
一个人的身影 2020-12-30 08:25

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 tri

3条回答
  •  -上瘾入骨i
    2020-12-30 09:15

    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;
    }
    

提交回复
热议问题