Dipose vs Destructor

S

Scott McFadden

I have a C++ CLI Managed DLL project which is consumed by C# clients.

What is the recommended way for ensuring proper clean up of managed
resources and native resources in a managed C++ class?

thanks

ScottM
 
J

Jochen Kalmbach [MVP]

Hi Scott!
I have a C++ CLI Managed DLL project which is consumed by C# clients.

What is the recommended way for ensuring proper clean up of managed
resources and native resources in a managed C++ class?

The same as for C# assemblies: IDisposable

--
Greetings
Jochen

My blog about Win32 and .NET
http://blog.kalmbachnet.de/
 
C

Carl Daniel [VC++ MVP]

Jochen said:
Hi Scott!


The same as for C# assemblies: IDisposable

Except that C++/CLI doesn't permit you to implement IDisposable. To quote
from (an early draft of) the C++/CLI specification (8.8.8/25):

C++/CLI implements the destructor and finalizer semantics in any ref class T
by using the CLI dispose pattern, which makes use of five functions
(Dispose(), Dispose(bool), Finalize(), __identifier("~T")(), and
__identifier("!T")()), all of whose definitions are generated by the
compiler, as required. These cleanup mechanisms are hidden from the C++/CLI
programmer.

In C++/CLI, the proper way to do cleanup is to place all of the cleanup code
in the destructor and finalizer, as follows:
.. The finalizer should clean up any resources that are represented by value
types ([CD]: e.g. HANDLEs to native resources).
.. The destructor should do the maximal cleanup possible. To facilitate this,
the programmer should call the finalizer from the destructor and write any
other cleanup code in the destructor. A destructor can safely access the
state of ref classes with references from the object, whereas a finalizer
cannot.

For ref classes, both the finalizer and destructor must be written so they
can be executed multiple times and on objects that have not been fully
constructed.

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top