Hello,
Does one need to delete pointers allocated with gcnew? Or does the
garbage collector do it?
I always though the garbage collector did it, but I saw this example
today on MSDN:
StreamReader^ sr = gcnew StreamReader( "TestFile.txt" );
try
{
String^ line;
// Read and display lines from the file until the end of
// the file is reached.
while ( line = sr->ReadLine() )
{
Console::WriteLine( line );
}
}
finally
{
if ( sr )
delete (IDisposable^)sr; // <-----DELETE HERE ???
}
Jochen Kalmbach [MVP] - 13 Nov 2007 19:08 GMT
Hi dogbert1793!
> Does one need to delete pointers allocated with gcnew? Or does the
> garbage collector do it?
gcnew => Garbage Collector NEW

Signature
Greetings
Jochen
My blog about Win32 and .NET
http://blog.kalmbachnet.de/
Ben Voigt [C++ MVP] - 13 Nov 2007 19:56 GMT
> Hello,
>
[quoted text clipped - 21 lines]
> delete (IDisposable^)sr; // <-----DELETE HERE ???
> }
That's just calling Dispose... not freeing the memory.
Also, that example would be much better using stack semantics:
StreamReader sr("TestFile.txt");
String^ line;
while (nullptr != (line = sr->ReadLine()))
Console::WriteLine(line);
/* automatic cleanup by compiler for all exit paths, including exceptions */
Mark Salsbery [MVP] - 13 Nov 2007 20:42 GMT
In addition to Ben's reply, you may want to take a look at this...
Destructors and Finalizers in Visual C++
http://msdn2.microsoft.com/en-us/library/ms177197(VS.80).aspx
Mark

Signature
Mark Salsbery
Microsoft MVP - Visual C++
> Hello,
>
[quoted text clipped - 21 lines]
> delete (IDisposable^)sr; // <-----DELETE HERE ???
> }