Pull request #6059 with a fix to memory handling

This is pull request #6059 with one small change to initialise a pointer to null.  Otherwise under certain conditions the destructor will delete a random memory location.  It was causing very bizarre crashes, I'd post the stack trace but since it affects a random memory location I don't think it's relevant.