More new/delete overriding fun.

Consider the following code snippet:

struct Foo
{
    void* operator new(size_t bytes);
    void operator delete(void* ptr);
};

struct Bar : public Foo
{
    void* operator new(size_t bytes);
    void operator delete(void* ptr);
};

[...]

Foo* b = new Bar();
delete b;

Can you see a problem here? Yes, there’s no virtual destructor. It will not manifest itself (at least under Visual Studio) in an obvious way if you do not do anything in derived class’ destructor. Imagine you dont want your class to have virtual destructor, or any virtual method for that matter, so that there’s no vtable. Why? Well, imagine you’re working with legacy codebase that’s using raw mem dumps for saving/loading data. You dont want to do any specific work in Foo’s destructor, so it’s OK now, right? Well, not quite, it turns out. In C++, virtual destructor is required to make compiler call valid operator delete (in our example above it will try to call Foo::operator delete). If you use pool-per-class for example, it’ll allocate memory from one pool and try to return it to another… All this silently, without single compile warning. Simple solution is of course to provide virtual destructor, but you’d have it here already if you could afford to, most probably. If you dont have vtable you’ll most probably use some custom way of determining instance type, so all there’s to do is finding valid pool type basing on that type.

Old comments

virtual destructor 2010-03-31 11:21:03

[…] Virtual; typically as empty method Implement their pointers, as the list stores dynamic objects …More new/delete overriding fun. | .mischief.mayhem.soap.Consider the following code snippet: struct Foo { void* operator new(size_t bytes); void operator […]