scope struct?

Steve Teale steve.teale at britseyeview.com
Sun Oct 16 21:47:36 PDT 2011


Is not needed because structs are inherently scope.

I'm sure experienced D programmers do this all the time when they want 
something done on exit from a scope, but I never had, and maybe there are 
others who haven't, particularly if coming from a C++ 'use classes for 
everything' background.

import std.stdio;

bool glob;

struct Sentinel
{
   void function() doit;
   bool already;
   this(void function() f)
   {
      doit = f;
      already = false;
   }

   ~this()
   {
      if (!already)
      {
         writeln("Doing it now");
         doit();
      }
      else
         writeln("Won't bother");
   }

   void dontBother() { already = true; }
}

void reset() { glob = false; }

void main(string[] args)
{
   glob = true;
   {
      Sentinel s = Sentinel(&reset);
      writeln("Doing stuff in the scope");
      if (args.length >= 2 && args[1] == "db")
         s.dontBother();
   }
   writeln(glob);
}


More information about the Digitalmars-d-learn mailing list