Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should overriding delete in C++ behave?

Tags:

The problem I'm running into is that as far as I know the delete operator should be a static function but sometimes the compiler (VC++) seems to be treating it as dynamic.

Given:

class Base
{
public:
  void* operator new(size_t size) { /* allocate from custom heap */ }
  void operator delete(void *p) { customFree(p, sizeof(Base)); }

  Base() {}
  virtual ~Base() {}
};

class Derived: public Base
{
public:
  void* operator new(size_t size) { /* allocate from custom heap */ }
  void operator delete(void *p) { customFree(p, sizeof(Derived)); }

  Derived() {}
  virtual ~Derived() {}
}

What I see happening is that deleting the base pointer will result in call to Derived::opeator delete.

Base *p = new Derived();
delete p; //calls Derived::operator delete

If I don't define ANY destructors then I get what I expected to happen: Base::operator delete is called. This seems to be happening because the compiler is inserting a function called 'scalar deleting destructor into the vtable when a destructor is defined. Then that function will call Derived::delete.

So I have to questions: 1) Is this standard behavior? 2) When should I be using

void operator delete( void *, size_t );

vs.

void operator delete( void * );

if the above is standard behavior?