2006-04-01

I recently read a long discussion about garbage collection in C++.

It's an interesting discussion to me, because I thought most experts already agreed that C++ was extremely hostile to garbage collection. And most of the C++ programmers involved in the thread seem to be at least a little bit skeptical. Possibly some of them take pride in being skillful enough to "manage their own memory"-- unflattering comparisons to Java were common.

Driving the discussion were the noted C++ expert Herb Sutter and a grad student named Andrei Alexandrescu. It was funny to see them sparring with some of the old-line C++ programmers like Jeremy Coffin.

One behavior that C++ has now which is kind of desirable is that the destructor for objects is called just as soon as the object goes out of scope. This makes it possible to use objects to manage scarce resources like network connections or mutexes, which you want to release as soon as you are done using. In most garbage collected languages, you do not have a good idea of when the "finalizer" (that's what the destructor is called in these languages) will be called, so you can't really use this "resource allocation is initialization" idiom as much.

I think C# has the best of both worlds, since it allows the programmer to specify this behavior for certain objects declared on the stack if he wants. I should check out C# some time-- it really has a lot of nice features, from what I hear.

2 Comments:

At 12:46 PM, Anonymous Anonymous said...

This makes it possible to use objects to manage scarce resources like network connections or mutexes, which you want to release as soon as you are done using. In most garbage collected languages, you do not have a good idea of when the "finalizer" (that's what the destructor is called in these languages) will be called, so you can't really use this "resource allocation is initialization" idiom as much.

It seems to me that relying on the unobvious specifics use of destructors is a pretty hackish. In places where it is important to release resources, it seems that the programmer should do this explicitly rather than the releasing being implicit in some destructor call.

In any case, it seems to from one more direction make the case that different languages are good for different things.

- rdore

 
At 4:36 AM, Blogger RareCactus said...

It seems to me that relying on the unobvious specifics use of destructors is a pretty hackish. In places where it is important to release resources, it seems that the programmer should do this explicitly rather than the releasing being implicit in some destructor call.

In C++, relying on destructors to release resources is not hackish. It's actually considered very good design, and it's a necessary part of making your code "exception-safe."

There's a column on exception safety, which probably has more info than you ever wanted to know, at http://www.gotw.ca/gotw/082.htm

 

Post a Comment

<< Home