What's wrong with this code?

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Sep 18 19:45:52 PDT 2015


On Saturday, 19 September 2015 at 02:30:39 UTC, Chris wrote:
> 			bmove.addOnClicked (delegate void (Button aux) {

What's the context of this call? If it is inside a struct and you 
are accessing local variables you can get in trouble because the 
context pointer may not be correct. You are using `vec` there, if 
`glw` is a struct/class member too, then the compiler can 
sometimes be a bit stupid about bringing in the correct `this` 
reference to the delegate.

Basically the problem is that a delegate only has one pointer 
inside to the data it needs. Usually, it points to the this for 
an object OR to a copy of the local variables. But since you want 
to access members of both, it is too stupid to handle that case 
and tries to access like this.glw through the local variable 
copy... where this and thus glw don't actually exist, which is 
why the debugger is saying what it is saying.

I've seen this before (and even briefly mentioned it in my dconf 
talk this year) and found three possible workaround solutions:

1) make some parts struct static. Probably not applicable to 
you...

2) use a temporary delegate to which you pass arguments 
explicitly, to make a copy of them in one spot

3) or, in a similar vein, make a local copy of the this variable 
or references you need and access parts through it.


I think #3 will work for you here. Right above that loop, try 
something like

auto glw = this.glw;


or something, maybe you will want to change names so it isn't as 
ambiguous.

But give that a try and run it again, I betcha you'll find some 
success.


> 		b.addOnValueChanged (delegate void (SpinButton aux) {
> 			for (int i = 0; i < 6; i++)
> 				sellimits [i] = selwidgets [i].getValueAsInt ();
>
> 			glw.set_sel_box (sellimits);
> 			glw.sel_active = 1;
> 			glw.actual_queue_draw ();
> 		});

See, here, you're just using glw, no local variables, to if it 
pulls the struct/class `this` as the delegate pointer, you'll be 
in business. That's why I suspect this is the issue.

> Could this be a compiler bug?

arguably, it should at least not compile and do the wrong thing.


More information about the Digitalmars-d-learn mailing list