【问题标题】:Will this memory issue happen if I instance a DLL class?如果我实例化一个 DLL 类,这个内存问题会发生吗?
【发布时间】:2011-01-10 07:55:53
【问题描述】:

关于 DLL 和不同版本的运行时,我有一些不清楚的地方。

我知道,例如,如果在我的 DLL 中我有这样的函数:

void deletePointer(int *something)
{
   delete something;
}

如果在我的 main() 函数中使用 new 分配了某些内容,这可能会导致问题。我不清楚的地方如下:

假设我在 DLL 中有一个类,我在 main 中实例化它,然后尝试再次执行此操作,它仍然是一个问题吗?

例如: //在我的DLL中

class Base
{
    void deletePointer(int *something)
    {
       delete something;
    }
}

//在exe中

int main()
{
  Base * base = new Base();
  int * myInt = new int(23);
   base->deletePointer(myInt); //is this a problem?
}

基本上我不清楚的是,如果我实例化删除指针的 DLL 类,运行时“分配它的人必须删除它”规则是否适用。

谢谢

【问题讨论】:

    标签: c++ dll


    【解决方案1】:

    是的,这可能会导致问题。你需要做的只是在你分配它的地方释放分配的内存。这可能意味着您需要实现在 DLL 中创建和删除类实例的方法;例如,如果您希望 DLL 创建/销毁 Base 实例,则:

    class Base
    {
        static Base *create();
        static void destroy(Base *b);
    
    }
    

    在exe中:

    int main()
    {
      Base *base = Base::create();
      // blah
      Base::destroy(base);
    }
    

    【讨论】:

    • 显然使用某种资源管理可以减轻您自己跟踪对象生命周期的繁琐负担。
    【解决方案2】:

    在这方面,DLL 中的普通函数和 DLL 的类实例的方法没有区别。所以它们会导致相同的行为。

    【讨论】:

      猜你喜欢
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-29
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多