使用 DLL 管理多态定时事件的内存

发布于 2024-10-10 20:53:35 字数 402 浏览 1 评论 0原文

这是我的问题。

我制作的 Gui 库支持定时事件。基本上,我有一个名为 TimedEvent 的类,用户从中继承。然后他们会这样做:

addTimedEvent(new DerivedTimedEvent(...));

但是考虑到定时事件的性质,我会在事后管理内存。

因此,当定时事件完成其任务时,我的库会对其调用删除。虽然它运行良好,但这是因为 exe 和库都是用 msvc 2008 构建的。我想如果我有 2 个版本的运行时,一个用于 lib,一个用于 exe,我可能会遇到麻烦。

我可以做什么来解决这个问题?我无法创建工厂,因为派生类型位于 exe 方面。我也不能要求用户调用删除,因为他们可能没有办法跟踪时间,或者知道事件是否因某种原因而延迟。

谢谢

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 for whatever reason.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一绘本一梦想 2024-10-17 20:53:35

尝试获取 Dellocator Functor 对象作为 TimedEvent 类的构造参数。现在,每个创建派生类的客户端都应该提供一个 Dellocator,您可以在删除对象时调用它。您还应该有默认的分配器函子,它只是作为特殊情况进行删除。

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);
}

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);
}
尾戒 2024-10-17 20:53:35

boost::shared_ptr 对象可以做到这一点。原因是删除器是在施工现场创建的,因此即使您已经运行了 c 运行时 fubar,也会调用适当的版本。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文