What happens is that one extra class is generated to hold the outer variable,
and another one is generated to hold an inner variable and a reference
to the first extra class. Essentially, each scope that contains a captured
variable gets its own type, with a reference to the next scope out that contains
a captured variable. In our case, there were two instances of the type
holding inner, and they both refer to the same instance of the type holding
outer. Other implementations may vary, but this is the most obvious
way of doing things.
Even after you understand this code fully, it??™s still quite a good template for experimenting
with other elements of captured variables. As we noted earlier, certain elements
of variable capture are implementation specific, and it??™s often useful to refer to
the specification to see what??™s guaranteed??”but it??™s also important to be able to just
play with code to see what happens.
It??™s possible that there are situations where code like listing 5.14 would be the simplest
and clearest way of expressing the desired behavior??”but I??™d have to see it to believe
it, and I??™d certainly want comments in the code to explain what would happen. So, when
is it appropriate to use captured variables, and what do you need to look out for?
5.5.7 Captured variable guidelines and summary
Hopefully this section has convinced you to be very careful with captured variables.
Pages:
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323