gcnew,

  • Thread starter Thread starter dogbert1793
  • Start date Start date
D

dogbert1793

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 ???
}
 
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 ???
}

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 */
 
Back
Top