DIP44: scope(class) and scope(struct)

H. S. Teoh hsteoh at quickfur.ath.cx
Fri Aug 23 18:23:04 PDT 2013


On Sat, Aug 24, 2013 at 03:06:39AM +0200, Andrej Mitrovic wrote:
> On Saturday, 24 August 2013 at 00:48:46 UTC, Andrej Mitrovic wrote:
> >On Saturday, 24 August 2013 at 00:45:46 UTC, H. S. Teoh wrote:
> >>Destroy! ;-)
> >
> >I won't destroy but I'll say avoid the struct/class keywords and
> >use `scope(this)` instead, it looks nicer and will work easier in
> >generic code.
> 
> Perhaps scope(~this) is actually more appropriate.

Hmm. You do have a point. But I'm not sure I like breaking the pattern
of a single identifier inside scope(). I still think scope(this) looks
nicer and is nicer to type as well. And also reads like "scope of this
object", which kinda conveys the intent.

But anyway, we can bikeshed over the exact syntax later. What of the
proposal itself? Does it make any sense? Any obvious glaring flaws?

Also, it just occurred to me that Adam's manual implementation can be
made to handle partial object construction as well, by using
scope(failure) in the ctor:

	struct S {
		void delegate()[] cleanupFuncs;
		Resource1 res1;
		// ...
		this() {
			// assuming the dtor isn't invoked if the ctor
			// throws.
			scope(failure) cleanup();

			res1 = acquireResource();
			cleanupFuncs ~= { res1.release(); }
			...
		}

		void cleanup() {
			foreach_reverse (f; cleanupFuncs)
				f();
		}

		~this() { cleanup(); }
	}

So scope(this) could simply be lowered to the above code, perhaps with
some compiler low-level handling for the potential problem with calling
a method from ~this(), which I think can be a problem in the current
implementation of dtors? (IIRC 'this' may be invalid when ~this() is
invoked, or something dangerous like that?)

In any case, the above code has a lot of boilerplate which scope(this)
would eliminate, besides expanding the concept of scope guards to object
lifetimes.


T

-- 
Unix was not designed to stop people from doing stupid things, because
that would also stop them from doing clever things. -- Doug Gwyn


More information about the Digitalmars-d mailing list