Question

I was making a memory pool allocator for a project I am working on. My pool allocator returns chunks of memory fine however my class inherits from another class.

    MyClass *fx = (MyClass*)pool->allocateEffect(sizeof(MyClass));
    *fx = MyClass();

This doesn't setup the vtable for me. I did some searching and found out the new operator can take in a chunk of memory.

    MyClass *fx = (MyClass*)pool->allocateEffect(sizeof(MyClass));
    fx = new(fx)MyClass();

And this will initialize the vptr. So I was wondering if there is anyway to allocate the vptr my self or is it strictly up to the compilers whim?

Was it helpful?

Solution

new(fx)MyClass()

This is called "placement new" and will actually call a constructor to actually create an object.

Until you created that object in the memory you allocated, it simply does not exist (as an object of that type) so it is just raw untyped memory that you cast to something, which results in undefined behavior.

I would suggest that you make your function a template like.

template<class T>
T* allocateEffect() { return new (allocate_some_memory(sizeof(T))) T(); }

adding proper variadic templates and forwarding for constructor arguments is left as an exercise to the reader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top