1

So I've written my own memory management class.

Essentially it allocates a big block of memory via malloc, then upon request it hands over the memory to the requester in the program (as you would expect.)

I've also implemented templated allocation and free functions, which explicitly calls the constructor and destructor based on the templatized class.

The problem, as you might already be realizing, is what about when I attempt to delete through a base pointer?

The templated function picks up the base class' type, and thus the base's virtual destructor is called, not the correct derived destructor.

There doesn't happen to be a placement delete or anything that would function like a regular "delete" command but not attempt to deallocate the memory?

E.S
  • 536
  • 1
  • 9
  • 20
sir_cakes
  • 13
  • 3
  • 1
    It seem you have no overload of new/delete in your base class –  Jan 27 '14 at 07:13
  • maybe take a look at this SO post http://stackoverflow.com/questions/461203/when-to-use-virtual-destructors – jon_shep Jan 27 '14 at 07:37

1 Answers1

2

You want to just call the destructor, something like:

myObjPtr->~MyClass()

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • Yes, I am explicitly calling the destructor, but it's of the base since that's what's being templatized by the pointer that's passed in. For example: class A { public: virtual ~A(); }; class B : public A { public: ~B() {} }; void main(void) { void* pMem = malloc(sizeof(B)); A *a = new(pMem) B(); //Suppose we don't explicitly know what's in 'a' at this point. a->~A(); } This is obviously an extremely oversimplified example, but you get the point. – sir_cakes Jan 27 '14 at 07:30
  • 2
    @user3239404 simply: `A* p = new B(); p->~A();` will cause `p->~B()` to be invoked since `~A()` is `virtual`. – Paul Evans Jan 27 '14 at 07:40
  • Okay awesome! It seemed like that's how it should be functioning but I was getting a runtime error on the destructor call. Something else must be going awry then. Thanks! – sir_cakes Jan 27 '14 at 07:50