0

Consider the following code.

#include <functional>
#include <stdio.h>
#include <stdlib.h>


std::function<void()> getFunction() {
    int foo = 0;
    return [&] () {
        printf("foo = %d\n", foo);
    };
}
int main(){
    std::function<void()> foo = getFunction();
    foo();
}

On my machine, it prints the following.

foo = 32767

Why does it not print 0?

merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • 1
    possible duplicate of [In C++11 Lambdas, what happens if I capture a local variable by reference, and it goes out of scope?](http://stackoverflow.com/questions/9488129/in-c11-lambdas-what-happens-if-i-capture-a-local-variable-by-reference-and-i). [This](http://stackoverflow.com/questions/12463269/c11-lambda-closure-involving-a-stack-variable-by-reference-that-leaves-scope-i) too. – user657267 Nov 04 '14 at 01:06

1 Answers1

0

It turns out, after consulting one of the other students in my lab, that if you want to capture a variable in a closure by reference, you must ensure that the said variable is still in scope at the time you try to access it. In particular, this means that you can pass a closure to a function call from the function getFunction() but not return it to another function. The closure above has an equivalent problem to returning a local variable by pointer.

Instead, one can use the value-capturing closure, although that means that the captured variables are read-only.

std::function<void()> getFunction() {
    int foo = 0;
    return [=] () { // Capture by value works
        printf("foo = %d\n", foo);
    };
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
  • `although that means that the captured variables are read-only` you can make the lambda `mutable` if you want to modify copy-captured entities. Then again all of this has been explained multiple times across other questions, did you try searching first? – user657267 Nov 04 '14 at 01:09
  • @user657267, Yes I did, but I did not find. :P – merlin2011 Nov 04 '14 at 01:26