Pointer to member variable again

Kirk McDonald kirklin.mcdonald at gmail.com
Tue Jul 29 09:07:16 PDT 2008


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.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list