Skip to content

Instantly share code, notes, and snippets.

@jbeardson
Last active May 26, 2018 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbeardson/6a7146d295e45723b982fa63a9f6259e to your computer and use it in GitHub Desktop.
Save jbeardson/6a7146d295e45723b982fa63a9f6259e to your computer and use it in GitHub Desktop.
C++ vs Delphi capture of local variables
program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils
, System.Generics.Collections
;
type
TFn = reference to procedure;
function createFn(i : integer) : TFn;
begin
result :=
procedure
begin
WriteLn(i);
end;
end;
var
vfn : TArray<TFn>;
i : integer;
fn : TFn;
begin
try
// This inline lambda definition capturing a local
// variable shows odd and unexpected behavior ...
for i := 0 to 9 do begin
vfn := vfn + [
procedure
begin
WriteLn(i);
end];
end;
for fn in vfn do begin
fn();
end;
// ... while this works just like intended
// (Thanks @dalijap for clarifying this)
vfn := [];
for i := 0 to 9 do begin
vfn := vfn + [createFn(i)];
end;
for fn in vfn do begin
fn();
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
#include <iostream>
#include <functional>
#include <vector>
int main() {
std::vector<std::function<void()>> vfn;
for(int i = 0; i < 10; ++i) {
vfn.push_back([i]() { std::cout << i << std::endl; });
}
for(auto fn : vfn) {
fn();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment