No need for "scoped" if you have "counted" (Re: auto storage class - infer or RAII?)

Bill Baxter dnewsgroup at billbaxter.com
Tue Nov 14 16:16:00 PST 2006


Boris Kolar wrote:
> == Quote from Sean Kelly (sean at f4.ca)'s article

> I like the above suggestions. After thinking about it, I'm beginning to wonder if
> scoped variables are usefull at all. The way I see it, there are three cases,
> where one might desire scoped variables:
> 
> 1. Guaranteed, deterministic finalization (mostly disposal of system resources).
> For example, file should be closed when going out of scope. In this case, it would
> be better to make File class scoped, not individual variables:
>     auto/scoped/whatever class File {
>         this() { ... }
>         ~this() { close; }
>     }

Wouldn't you like to be able to return a file object from a function? 
You wouldn't be able to if all File objects were destroyed as soon as 
the went out of scope.

Anyway, thinking about it, "scoped" is kind of a limited concept.  Take 
one variable in one scope and destroy it as soon as that scope ends. 
You can't return something like that, you can't really meaningfully 
assign it to other things that way.

A more general concept would be to have something that is guaranteed to 
run its destructor as soon as there are no outstanding references. 
That's actually a lot simpler to do than general garbage collection. 
You just count references.  It's exactly what boost::shared_ptr does.

GC covers *most* cases where people use shared_ptr in C++ -- and in a 
much cleaner and potentially more efficient way.  But the cases where 
you want something cleaned up as soon as not in use are not handled so 
well by GC.  This includes "scoped" as one particular case.

So what about "counted" instead of "scoped"?

I guess this has the same issues as scoped (because scoped is basically 
just a binary refcount).  Namely, do you attach it to the class or to 
the instance?

In any event I think boost::shared_ptr / weak_ptr type functionality 
would be useful in D, but I don't see how to implement it cleanly as a 
library without an opAssign to keep track of the reference.

--bb



More information about the Digitalmars-d mailing list