Wednesday, 14 March 2018

.net - How do you dispose of an IDisposable in Managed C++



I'm trying to Dispose of an IDisposable object(FileStream^ fs) in managed C++ (.Net 2.0) and am getting the error



'Dispose' : is not a member of 'System::IO::FileStream'



It says that I should invoke the destructor instead. Will calling



fs->~FileStream();


call the dispose method on the FileStream object? Why can't I call Dispose?


Answer



The correct pattern is to just delete the object:




delete fs;


This will be translated into a call to Dispose()



See this post for some of the details of what is going on under the hood. The advantage of this idiom is that it allows you to write:



{
FileStream fs(...)
...

}


And have the Dispose method called correctly ... equivalent to a using block in C#. The file stream object is still allocated on the managed heap.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...