Overriding new and delete for plugin libraries

Hi everyone,

I'm looking at developing a plug-in application and I've read in a few places that memory must be allocated and deallocated by the same executable or risk that dreaded thing: undefined behaviour. You typically see factory functions used to create a new heap object and return the pointer (either naked or smart), but because the plug-in library is allocating the memory, there must be a way of deallocating it in all circumstances via the plug-in executable as well.

Smart pointers are "easy" as templates like shared_ptr (either boost, tr1 or C++11) support custom deleters, but there are times when you need to pass naked pointers: I'm using a GUI toolkit that assigns manages child widgets through naked pointers, but these would almost certainly be deleted from the main app side...crash waiting to happen.

My thoughts were to override the new and delete operators on the classes I'm sending to the GUI, that are simply implemented to use the global operators on the plug-in side, like this:

PluginPanel.h
1
2
3
4
5
6
7
class PluginPanel : public GuiPanel
{
public:
    void *operator new(std::size_t n);
    void operator delete(void *p);
    // More class functions etc...
}

PluginPanel.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "PluginPanel.h"

void *PluginPanel::operator new(std::size_t n)
{
    return ::operator new(n);
}

void PluginPanel::operator delete(void *p)
{
    ::operator delete(p);
}

// Class function implementations etc... 


Is this an acceptable solution and would it work?

Many thanks,

Richard ~
Last edited on
Topic archived. No new replies allowed.