Variable binding

Top  Previous  Next

New features since Delphi 7 > Anonymous Methods > Variable binding

 

There is a subtle difference between anonymous methods and lambda expressions: while anonymous methods extend the lifetime of captured references, this is not the case for lambda expressions. In the following Delphi code snippet the anonymous method, which is assigned to the variable adder, binds the value 20 to the parameter variable y.The lifetime of y is extended in Delphi, until adder is destroyed.

 

 

type

  TFuncOfInt = reference to function(x: Integer): Integer;

 

function MakeAdder(y: Integer): TFuncOfInt;

begin

Result := function(x: Integer) : Integer

  begin

    Result := x + y;

    end;

end;

 

procedure TestAnonymous1; 

var

  adder: TFuncOfInt;

begin

  adder := MakeAdder(20);

  Writeln(adder(22)); 

end;

 

->

 

typedef std::function<int (int)> TFuncOfInt;

 

TFuncOfInt MakeAdder(int Y)

{

  TFuncOfInt result;

  result = [&](int X) -> int {  // => error

  int result = 0;

  result = X + Y;

  return result;

  };

  return result;

}

//---------------------------------------------------------------------------

void Test()

{

  TFuncOfInt adder;

  adder = MakeAdder(20);

  WriteLn(adder(22)); 

}

 

 

Lambda expression capture variables either by reference or as copies. The C++ code that Delphi2Cpp generates, always uses the most general capture [&], which binds all used variables as references. But in the example above the lifetime of y isn't extended. Therefore y has an accidental value, when adder is called. In this case the code can be corrected easily, by use of a copying capture:

 

result = [y](int X) -> int {

 

binding just y or

 

result = [=}(int X) -> int {

 

binding all used variables, here just y too.

 

 

 

 

 

 

 

 

 

 

 

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content