According to this article, http://msdn.microsoft.com/en-us/library/ms177197.aspx on MSDN, we should release the unmanaged resources in the finalizer and managed resources in the destructor. I.e. following pattern:
// destructor开发者_运维百科s_finalizers_1.cpp
// compile with: /clr /c
ref struct A {
// destructor cleans up all resources
~A() {
// clean up code to release managed resource
// ...
// to avoid code duplication
// call finalizer to release unmanaged resources
this->!A();
}
// finalizer cleans up unmanaged resources
// destructor or garbage collector will
// clean up managed resources
!A() {
// clean up code to release unmanaged resource
// ...
}
};
Why not just put it all in the destructor and scrap the finalizer? Is it because there is a possibility that the object could still be indeterministically cleaned up by the garbage collector?
Because if you skip the destructor call (e.g. by not using RAII) then your unmanaged resources will leak, and the .NET runtime can't do anything about them.
If you clean up your unmanaged resources in the finalizer, then the runtime will run this even if you mess your code up and let your object reference fly off somewhere :)
Basically, if your code is buggy you can't count on the destructor being called, but the finalizer will always be called when the object is reclaimed by the garbage collector.
精彩评论