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.




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


function MakeAdder(y: Integer): TFuncOfInt;


Result := function(x: Integer) : Integer


    Result := x + y;




procedure TestAnonymous1; 


  adder: TFuncOfInt;


  adder := MakeAdder(20);






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);





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