Last active
May 26, 2018 11:48
-
-
Save jbeardson/6a7146d295e45723b982fa63a9f6259e to your computer and use it in GitHub Desktop.
C++ vs Delphi capture of local variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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