Auto objects and scope
Bill Baxter
dnewsgroup at billbaxter.com
Thu Nov 16 18:02:49 PST 2006
genie wrote:
> Forgive my ignorance, guys, but there is something in GC for D I
> can't spin my head about - look at this bit of code:
>
> Test tst=new Test;
>
> ...
> if(b)
> {
> auto Test t1=new Test;
> ...
> tst=t1;
> }
> ...
> tst.func();
>
> auto modifier forces the object to be deleted even though it was
> assigned to something else before leaving the scope - is this
> behaviour correct?
>
> Gene
Yep. auto (now 'scope') is not a reference counter. It just says
delete this one variable when this one variable goes out of scope.
I think it's more or less equivalent to "scope(exit) delete t1;".
In fact it will merrily delete whatever t1 happens to point to at the
end of the scope:
---------------------------
import std.stdio : writefln;
class C {
this(char[]n) { name=n; }
~this() { writefln("Bye bye: ", name); }
char [] name;
}
void main()
{
auto a = new C("a");
{
auto scope b = new C("b");
b=a;
writefln("Leaving scope...");
}
writefln("Left scope.");
writefln("Ending main");
}
/*
Output:
Leaving scope...
Bye bye: a
Left scope.
Ending main
Bye bye: b
*/
a gets deleted at the end of the scope instead of b, and b only gets
cleaned up later by the final garbage collection sweep.
So it seems it really is just syntactic sugar for the scope(exit) statement.
I think some sort of reference-counting construct is needed for the type
of cases your example illustrates. For things like File objects, you
want to be able to return them, but you want them to be cleaned up
immediately when no longer in use. 'scope' is too limited I think.
I'm not sure how to do it though. It's not clear how to do in a clean
way as a library (like a shared_ptr!()) without an overloadable opAssign.
--bb
More information about the Digitalmars-d
mailing list