Sdílet prostřednictvím


The object lifetime issue is the same in C++, Java, C#

I’m going to echo various interesting pieces of newsgroup discussion here. Check out the newsgroups for the full threads.

On comp.lang.c++.moderated, Dietmar Kuehl <dietmar_kuehl@yahoo.com> wrote:

I have thought about integrating GC into C++ for quite some time. My personal conclusion was, however, that deterministic destruction and garbage collection don't really mix. The major issue is that in a truly garbage collected system you could simple use whatever reference you get hold of. This promise does not hold if deterministic destructors are involved.

I would dispute that characterization of a "truly garbage-collected system" -- it certainly doesn't describe either Java or .NET. In Java and C#, you routinely have objects to which you still have references but whose lifetimes have ended via the Dispose and using patterns, and you have to know (or the member functions have to check) that you're not using an already-disposed object.

The C++ destructor model is exactly the same as the Dispose and using patterns, except that it is far easier to use and a direct language feature and correct by default, instead of a coding pattern that is off by default and causing correctness or performance problems when it is forgotten.

So yes, in ISO C++ or Java or C# or C++ with C++/CLI, if you use a * or ^ or object reference to an object which has been Disposed/destroyed, you have exactly the same issue in all of those languages and environments: You need to be aware when pointers/references are invalidated. It's just the same as C++'s plain old pointer invalidation problem.

Comments

  • Anonymous
    July 31, 2004
    The difference is, because you don't have to worry about object lifetime in Java/C¤, people tend to forget to do it, and lets the GC handle it, and there we are...

    Where as a language, like C++, which enforces it more strongly, you are not as inclined to fall in that trap.

    Also I believe the recomendation for C¤ is to only worry about those objects that really matter, and dispose those approriately, leaving the rest to the GC.

    Most people tend to forget that the GC is simple a guard against objects you accidently forget about, instead of having them leaking resources, which is the appropriate way to do things in my opinion, as you say, although you use the word coding pattern to confuse something simple with something that sounds trickier.