The difference between a destructor and a finalizer?

后端 未结 4 2164
迷失自我
迷失自我 2020-12-08 19:09

Please Note: This question is about the difference in terminology between the words \"destructor\" and \"finalizer\" and their correct usage. I have merely provided

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 19:42

    Strictly speaking C# doesn't have a destructor (I believe the C# spec is confusing on this point). C#'s finalizer looks like a C++ destructor but, as you say, is non-deterministic. C# has deterministic clean-up in the form of IDisposable::Dispose (but this is still not called a destructor).

    C++/CLI has deterministic destructors, which look like C++ destructors. At the CLI level these map onto IDisposable::Dispose() (IDisposable is implemented for you ). C++/CLI has non-deterministic finalizers, which look like destructors but use the ! prefix instead of the ^ prefix.

    The fact that C++/CLI uses the same syntax for destructors that C# uses for finalizers can be a little confusing - but it fits better with C++, which has a strong tradition of deterministic destruction.

    Unfortunately the lack of universal definitions of these terms means you always need to clarify what you are talking about. Personally I always use the word finalizer when talking about the C# concept and reserve destructor for contexts where it definitely implies deterministic destruction.

    [Update] Since my original post here Eric Lippert has posted his response (the accepted answer) and followed up with a blog post on the same. I'm glad to see we're in agreement :-)

提交回复
热议问题