Extending "scope"

Brian White bcwhite at pobox.com
Sun Apr 6 01:36:15 PDT 2008


I wrote something about "GC vs delete", but after thinking about it some 
more, how about this...

There seems to be a fundamental conflict between RAII and the garbage 
collector.  You can assign a new object to a "scope" variable to cause 
it to get destructed without waiting for the GC, but what about objects 
within that?  For example:

class tBar {
     this()
     {
         writeln("a bar has been constructed");
     }
     ~this()
     {
         writeln("a bar has been destructed");
     }
}

class tFoo {
     scope tBar bar;

     this()
     {
         bar = new tBar();
         writeln("a foo has been constructed");
     }
     ~this()
     {
         delete bar;
         writeln("a foo has been destructed");
     }
}

unittest {
     auto foo = new tFoo();
}


If you run this, you'll get:

a bar has been constructed
a foo has been constructed

At some point, you _may_ also get:

a bar has been destructed
a foo has been destructed


When it comes to RAII, that's not enough.  Walter has allowed us to 
specify a class as being "scope" which requires you to create them with 
"scope auto foo = new tFoo()".  However, if I also add that property to 
"tBar", it won't compile.

scope class tBar {
     this()
     {
         writeln("a bar has been constructed");
     }
     ~this()
     {
         writeln("a bar has been destructed");
     }
}

scope class tFoo {
     tBar bar;

     this()
     {
         bar = new tBar();
         writeln("a foo has been constructed");
     }
     ~this()
     {
         delete bar;
         writeln("a foo has been destructed");
     }
}

unittest {
     scope auto foo = new tFoo();
}

$ dmd ...
test.d(32): variable socket_test.tFoo.bar globals, statics, fields, 
manifest constants, ref and out parameters cannot be auto
test.d(32): variable socket_test.tFoo.bar reference to scope class must 
be scope

Nor can I declare a member variable "scope tBar bar" within class tFoo. 
  In other words, it's not possible to embed one enforced RAII object 
within another.


What do others think about extending "scope" to allow it to be applied 
to member data?  They would by default be set to "null" but have the 
requirement that they must be set exactly once in the constructor and 
nowhere else.  They would also be deleted automatically during the 
destructor.

Or...  Is there a different way to accomplish this?

-- Brian



More information about the Digitalmars-d mailing list