开发者

Will this memory issue happen if I instance a DLL class?

开发者 https://www.devze.com 2023-02-03 14:55 出处:网络
There is something I\'m unclear about regarding DLL\'s and different versions of the runtime. I know that if for example, in my DLL I had a function like this:开发者_C百科

There is something I'm unclear about regarding DLL's and different versions of the runtime.

I know that if for example, in my DLL I had a function like this:开发者_C百科

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

if something had been allocated using new in my main() function, this could cause a problem. Where I'm not clear on is the following:

say I have a class in the DLL and I instance it in main, then try do do this again, will it still be a problem?

Ex: //in my DLL

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

//in exe

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

Basically what I am unclear on is if the runtime "he who allocated it, must delete it" rule applies if I instance the DLL class that deletes the pointer.

Thanks


Yes that could cause a problem. What you need to do is simply free allocated memory in the place you allocated it. This might mean you need to implement methods to create and delete the class instances within the DLL; for example if you wanted the DLL to create/destroy instances of Base, then:

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

}

in exe:

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


In this regards there is no difference between a normal function in a DLL and a method of a class instance of a DLL. So they would result in the same behaviour.

0

精彩评论

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