Tuesday, June 28, 2016

When Lambda capture by reference goes wrong

Here is a code that demonstrates lambda capture by value vs reference:

Running this code would yield 4.

When line 10 is used instead of line 9, running this code yields 10 instead of 4.

Ideally, 4 should be returned as the remainder of 10 divided by 6. If line 10 is used, however, the lambda function created encloses a reference to the variable x which goes out of scope as soon as the function add_func() completes execution.

After add_func() is called, the lambda function stored inside the vector uses a reference to x which is no longer valid (x only exists while add_func() is being executed). Therefore, the lambda function uses a reference to a variable with undefined value. Calling the lambda function therefore will yield to undefined results.

No comments:

Post a Comment