开发者

Managing memory of polymorphic timed events with DLL

Here is my issue.

My Gui library that I made supports timed events. Basically, I have a class called TimedEvent which users inherit from. They then do:

addTimedEvent(new DerivedTimedEvent(...));

However given the nature of timed events, I manage the memory afterwards.

So when the timed event has done its thing, my library calls delete on it. Although it runs fine, that is because the exe and the library were both built with msvc 2008. I think I might have trouble if I have 2 versions of the runtime, one for the lib, and one for the exe.

What can I do to fix this? I can't create a factory because the derived type is on the exe side of things. I also cannot ask the user to call delete since they might not have a way to keep track of time, or know if the event was delayed f开发者_JS百科or whatever reason.

Thanks


Try getting a Dellocator Functor object as construction parameter for your TimedEvent class. Now every client creating a derived class is expected to provied a Dellocator which you can call while deleting the object. You should also have default dellocator functor which simply deletes as a special case.

class base;

class Deallocator {
    void operator()(base* ptr) 
    {
        delete ptr;
    }
}

class base {
public:
base(Deallocator dealloc) 
{
    m_deleteFunc = dealloc;
}
~base() 
{
    m_deleteFunc(this);
}

private:
Deallocator m_deleteFunc;
}

int main
{
    Deallocator deletefunc;

    base baseObj(deletefunc);
}


The boost::shared_ptr object can do it. The reason being that the deleter is created at the construction site, so the appropriate version will be called even if you've got the c runtime fubar going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜