'Is it okay to delete an object that is created in the app from dll
I have a dll with a class that uses an abstract class for customizing the behaviour and it also has an implementation defined in dll
With this the app allocates a Child object and passes it into the class A which it deallocates the object when it is deleted
Can deleting an object that is created in the app from the dll create a problem if it does any idea of fixing it
The code roughly translates into this
// Dll
DLLEXPORT class A
{
private:
Base* ptr;
public:
A(Base* ptr) { this->ptr = ptr; };
~A() { delete ptr; }
};
DLLEXPORT class Base
{
virtual int foo() = 0;
};
DLLEXPORT class Child : public Base
{
virtual int foo() { return 1; }
};
// App
int main()
{
A obj(new Child);
return 0;
}
Solution 1:[1]
MS says this:
The DLL allocates memory from the virtual address space of the calling process (docs)
And in this answer you can see:
If your DLL allocates memory using C++ functions, it will do so by calling operator new in the C++ runtime DLL. That memory must be returned by calling operator delete in the (same) C++ runtime DLL. Again, it doesn't matter who does that.
You can have trouble if the DLL, c++ runtime and/or app are compiled with a different compiler; or if some of those are compiled statically.
To avoid those problems, you can pass a "deleter" object/function to the DLL so it makes the deletion in the app:
DLL:
class Base;
typedef void (*deleter_t)(Base * ptr);
deleter_t app_deleter {nullptr};
DLLEXPORT class A
{
private:
Base* ptr;
public:
A(Base* ptr) { this->ptr = ptr; };
~A() { app_deleter(ptr); }
};
DLLEXPORT void set_deleter (deleter_t func)
{
app_deleter = func;
}
APP:
void deleter (Base * obj)
{
delete obj;
}
int main()
{
set_deleter (deleter);
A obj(new Child);
return 0;
}
Solution 2:[2]
You can follow the Cpp Core Guidelines conventions to specify the transfere of ownership of the resource to make it clear what happens.
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rr-owner
There is also a lot of other good guidelines in there, like using initialization instead of assignment of member variables.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manuel |
| Solution 2 | Goswin von Brederlow |
