www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - Wrong implicit delegate conversion?

reply Manfred Nowak <svv1999 hotmail.com> writes:
Here a delegate from class C seems to be implicitely converted to a 
delegate of the module.

import std.stdio;
alias void delegate( int , inout int) GETTER;
class C{
  int i=3;
  GETTER getter(){
    return delegate void(int i, inout int o){ o= 2*this.i;};
  }
 }
void main(){
  auto c= new C;
  int i=0;
  c.getter()(0,i);
  writefln( i); //works: outputs 6
  GETTER q= c.getter(); // implicit conversion?
  q(0, i);
  writefln( i); //random result
}

-manfred
Feb 23 2007
parent reply Frits van Bommel <fvbommel REMwOVExCAPSs.nl> writes:
Manfred Nowak wrote:
 Here a delegate from class C seems to be implicitely converted to a 
 delegate of the module.
 
 import std.stdio;
 alias void delegate( int , inout int) GETTER;
 class C{
   int i=3;
   GETTER getter(){
     return delegate void(int i, inout int o){ o= 2*this.i;};
   }
  }
 void main(){
   auto c= new C;
   int i=0;
   c.getter()(0,i);
   writefln( i); //works: outputs 6
   GETTER q= c.getter(); // implicit conversion?
   q(0, i);
   writefln( i); //random result
 }

First off, on my machine (DMD/Linux): --- urxae urxae:~/tmp$ dmd -run test.d 269043800 125854208 --- The delegate isn't one 'of' the class. It's 'of' the C.getter() stack frame, which means it's invalid after the getter() function returned. *Never*[1] return a delegate literal from a function. Unpredictable results will follow. And what exactly do you mean by "a delegate of the module"? AFAIK there is no such thing. [1]: Well, at least not until Walter implements full closures that capture local variables.
Feb 23 2007
parent Manfred Nowak <svv1999 hotmail.com> writes:
Frits van Bommel wrote
 it's invalid after the getter() function returned.

 And what exactly do you mean by "a delegate of the module"? AFAIK
 there is no such thing.

Thank you, you are right with both remarks. I was simply unable to detect my own fault. -manfred
Feb 23 2007