How do you dispose of an IDisposable in Managed C++

我的梦境 提交于 2019-12-30 07:54:07

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/350052/how-do-you-dispose-of-an-idisposable-in-managed-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!