When I'm learning using abstract interface to encapsulate code in dynamic library, it seems that using "Release()" function to release resource is recommended. Now I'm wondering why they don't just use destructor to release? Is there any problem using destructor to release resource, or they just mean to use smart pointer?
This is the code recommended:
// Interface like that ..
struct IXyz
{
virtual int Foo(int n) = 0;
virtual void Release() = 0;
};
// Xyz class definition, derived from IXyz
// ...
// Using in client ..
IXyz* pXyz = GetXyz(); //Use Factory function to create an object
if(pXyz)
{
pXyz->Foo(42);
pXyz->Release();
pXyz = nullptr;
}
now I want to write the following code instead:
// Interface
struct IXyz
{
virtual int Foo(int n) = 0;
virtual ~IXyz() {}; // I have moved Release()'s content into Xyz's destructor
};
// Client
IXyz* pXyz = GetXyz(); //Use Factory function to create an object
if(pXyz)
{
pXyz->Foo(42);
pXyz->~IXyz();
pXyz = nullptr;
}
These code can both work correctly. So I'm wondering the differences between those two ways to release resources. Can I use both of them? Thanks a lot!