KevinHall

I have just been learning about finalizers in C++/CLI and saw quite a bit of sample code that duplicated the same resource-freeing code in both the destructor and finalizer. It seems obvious to me that I should put the resource-freeing code in a single place -- another private member function (see sample code at the end of this message).

So I have to questions:

  1. Am I doing the correct thing in this sample code Am I missing any important concept
  2. Is there a recommended standard name for the C++/CLI member function to free resources

Many thanks for your help!

- Kevin Hall

ref class Resource
{
private:
// Is there a recommended standard
// name for this member function

void
FreeResources()
{
Console::WriteLine(L"Freeing resources...");
}


public
:
virtual ~Resource() // IDisposable
{
FreeResources();
}

protected:
!Resource() // Finalize
{
FreeResources();
}
};




Re: Visual C++ General Is there a recommended standard name for a C++/CLI member function to free resources?

Chuck the Code Monkey

This is the correct way to do it because Dispose and Finalize do the same thing, only Dispose can be called by a user where Finalize is to be called by the garbage collector. And as far as I know there is no standard naming scheme for the cleanup method. A nice feature of the C++/CLI compiler is when the compiler generates the IL for the destructor (translated to Dispose() ), the GC::SuppressFinalize method is automatically called so you don't have to worry about the finalizer getting called in addition to the dispose method (as can happen in C# and VB.NET)

- Chuck Atkins





Re: Visual C++ General Is there a recommended standard name for a C++/CLI member function to free resources?

KevinHall

Great. Many thanks for the information!




Re: Visual C++ General Is there a recommended standard name for a C++/CLI member function to free resources?

djdowd

why not this

public:
virtual ~Resource() // IDisposable
{
this->!Resource();
}

protected:
!Resource() // Finalize
{
FreeResources();
}





Re: Visual C++ General Is there a recommended standard name for a C++/CLI member function to free resources?

djdowd

which, as I understand, get's translated by the compiler to become

public:
void Dispose() // IDisposable
{
System::GC::SuppressFinalize(this);
Finalize();
}

protected:
void Finalize() // Finalize
{
FreeResources();
}





Re: Visual C++ General Is there a recommended standard name for a C++/CLI member function to free resources?

KevinHall

Yeah, I suppose that will work.

Thanks!






Re: Visual C++ General Is there a recommended standard name for a C++/CLI member function to free resources?

djdowd

actually, i recall now it didn't work.

believe i changed it to:

(*this).!Resource()