Pointer to member variable again

Steven Schveighoffer schveiguy at yahoo.com
Tue Jul 29 10:45:53 PDT 2008


"Kirk McDonald" wrote
> Steven Schveighoffer wrote:
>> "ws" wrote
>>
>>>Suppose i have the following:
>>>
>>>int function() fp;
>>>int *ptr;
>>>class Cls
>>>{
>>>int k;
>>>int foo()  {  return 0;  }
>>>}
>>>
>>>void main()
>>>{
>>>fp = &Cls.foo;
>>>
>>>Cls c = new Cls;
>>>ptr = &c.k;  // <-- why always need a new instance?
>>>}
>>>
>>>As compared to delegate, is there no analogous way to specify this?
>>>
>>>ptr = &Cls.k
>>>
>>>Thanks!
>>
>>
>> In fact, this should fail to compile.  The fact that it succeeds is a 
>> bug. You should enter it in bugzilla (is it already there?)
>>
>> Did you try running it?  I get a segfault.
>>
>> fp is a member function, which means it needs a hidden 'this' pointer. 
>> When you assign &Cls.foo to fp, this should result in the same error as 
>> if you typed Cls.foo():
>>
>> Error: need 'this' to access member foo
>>
>> -Steve
>
> A direct, C++-style pointer-to-member-function is occasionally useful. 
> (Though rarely, since delegates are more useful nearly every time.) 
> Allowing this syntax is the only sensible way to get access to them. The 
> resulting pointer can then manually be shoved into a delegate:
>
> void function() fp = &Cls.foo;
> Cls c = new Cls;
> void delegate() dg;
> dg.funcptr = fp;
> dg.ptr = c; // I forget if a cast to void* is necessary...
> dg();
>
> Pyd relies on this behavior to implement its class wrapping, and it would 
> be fairly inconvenient if it went away.

I had no idea you could build delegates this way.  But even still, the 
function signature is not correct, it should be something like:

void function(Cls c) fp = &Cls.foo;

But in any case, the original code seems like dangerous behavior to allow 
without casting.  There should at least be a cast involved so the user is 
forced to say "yes, I know that the function signature isn't correct, do it 
anyways".  I still say this should be a bug.

-Steve 




More information about the Digitalmars-d-learn mailing list