delegate !is null

Saaa empty at needmail.com
Tue Sep 8 13:15:49 PDT 2009


>>> Hm... I'm still confused.  Why not just set the delegate to null?  Why
>>> do
>>> you need to have the delegate set to something?
>> It is for the gui. I give it a list of things to display.
>> And some of these things don't yet exist or can be deleted at any time.
>> I'd like it to display the last valid value.
>
> That still doesn't explain why you need to have delegates set to something 
> valid, yet have a null pointer value.
> Either a) you are trying to subvert  the type system, or b) you can simply 
> set the whole delegate (function and  pointer) once you get the class 
> instance.
>
> It's hard for me to say what is the best way to do it, but generally, 
> things like this are difficult, and rightfully so.  Having a delegate 
> without a valid pointer makes little sense.
>
>>
>>>
>>> There are ways to do it, without having a class instance, but it is 
>>> messy.
>> how messy? :D
>
> class C
> {
>   int val = 0;
>   int method() {return val;}
> }
>
> int delegate() dg;
>
> dg.func = &C.method; // note the upper-case C
That's actually quite nice, I didn't know it worked like that :)

>
> // dg is now a "instanceless" delegate to C.method.
>
> dg.ptr = new C;
So, nothing special under the hood, this would also work?
C c= new C;
dg.ptr = c;

>
> Now you can call dg() and it will call the C.method function on the newly 
> created C object.
>
> Note that this method of manipulating methods does NOT obey inheritance. 
> For example:
>
> class B : C
> {
>   int method() {return 555;}
> }
>
> dg.ptr = new B;
>
> dg(); // will return 0, since it calls C's version of method.
>
> I also don't know how well it will work on interfaces.
Very nice :)
Might be useful, thanks.

>
>> Kind of related:
>> If you delete an object and later create a new object, what are the 
>> chances
>> they are located on the
>> same place (deleted.ptr is new.ptr) ?
>> Does the garbage collector try to reuse locations or is it the opposite 
>> (or
>> random) ?
>
> The chances are non-zero :)
Are you quite sure there?
I'm only asking a single 'new'.
I mean, there could be some heuristic which would prevent the a new object 
to take the place of the latest deleted one.

> I wouldn't depend on this behavior either way  if I were you.
Yeah you're right, as long as something like this isn't part of the spec it 
wouldn't be safe.
Plus it shouldn't be part of the spec as it would be too stringent on the gc 
implementation in my opinion.
Just curious :)




More information about the Digitalmars-d-learn mailing list