[Issue 21633] New: anonymous class local scope confusion

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Feb 13 02:09:25 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=21633

          Issue ID: 21633
           Summary: anonymous class local scope confusion
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: dmd
          Assignee: nobody at puremagic.com
          Reporter: destructionator at gmail.com

Can you guess what this code does:

---

class A { int a; }

A createMyClass() {
    int a;
    return new class A { this() { this.a = a; } };
}

---

It is a self-assignment, since `a` inside the anonymous class refers to
`this.a`, not the immediately-obvious local variable.

Here, you probably saw it kinda quickly, but now imagine class A was out of
sight, out of mind and the variable was some protected thing or something you
would barely think about. That happened to me recently and I was perplexed for
a while.

dmd's behavior isn't wrong per spec, thus I'm calling this an enhancement, but
it certainly isn't useful to have code that looks right, compiles just fine,
but then does nothing.

Perhaps ALL self-assignments should be an error, but that'd probably be a pain
in the butt. This pattern though surely should be *something* since it
definitely isn't what I'd ever intend to write intentionally.

Moreover, there's currently no way to actually access that local `a` inside
that constructor. Just have to rename the variable when the silent conflict is
diagnosed. Not fun.

--


More information about the Digitalmars-d-bugs mailing list