Capturing callbacks in a C++ Lambda

Due to WinRT file access being completely asynchronous and requiring PPL, I've found myself writing a lot of continuation passing style code in C++ lately. Most of my current loader code involves passing a function that handles the results of the previous function, and these can go quite deep. When writing this kind of code, C++ lambdas are great, since you can define what you want to do with the result quite flexibly.

It also means you need to be careful about how you capture variables in those lambdas, particularly the continuations passed to the current function. They are likely also lambdas, and thus only exist by reference so long as the calling function does. PPL is actually threaded and asynchronous, so if you're interacting with the WinRT filesystem, there's a good chance you'll lose your calling context via being dispatched on another thread. Thus, be careful of capturing continuations by reference, and be aware you may have to pay the cost of capturing them by value.

social