1

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?

Sergey L.
  • 21,822
  • 5
  • 49
  • 75
user1659134
  • 93
  • 2
  • 7
  • 2
    The line fx = new (fx) MyClass(); is called placement new, you can put it in your allocateEffect method and make this method a templated method to get the class for using with placement new – Johnmph Apr 29 '14 at 15:07

1 Answers1

4
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.

Casey
  • 41,449
  • 7
  • 95
  • 125
PlasmaHH
  • 15,673
  • 5
  • 44
  • 57
  • Thanks, didn't know it was called placement new. Does this mean there is no other way to muck around with the vfptr of a block of memory? I see, really interesting. could you link to this post and ill vote it as answer http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new or just mention its a c++ standard – user1659134 Apr 29 '14 at 15:12
  • 2
    @user1659134: The vfptr is set _during the constructor_. If the constructor hasn't been called, then the object doesn't technically exist, so it's not an issue. placement new is just a way of calling the constructor at a preallocated location in memory. – Mooing Duck Apr 29 '14 at 23:58
  • forwarding constructor arguments + exception safety http://coliru.stacked-crooked.com/a/b408eafc1b96c92a – Mooing Duck Apr 30 '14 at 00:02
  • @MooingDuck Thanks I did roughly the same thing earlier today – user1659134 Apr 30 '14 at 02:54