Search code examples
c++lambdascoping

Will lambda run out of scope if returned


I have a struct which takes a function or callable object as input:

struct House {
  std::function<int()> colorSelector;
}

Now I assign in this way:

House getHouse() {
  House h;
  int color = 10;
  h.colorSelector = [&]() {
    return color;
  }
  return h;
}

Will I run into scoping issue? As after getHouse returns, color (local variable) will be destroyed?


Solution

  • Will I run into scoping issue?

    Yes.

    Your lambda captures color by reference, and after getHouse returns, the stack unwinds, and further accesses to color are undefined behavior.

    You should capture color by value to avoid such an issue.

    h.colorSelector = [color]() {
      return color;
    }
    

    If you need to refer to the same color, perhaps you want to allocate a std::shared_ptr<color> somewhere, and capture a copy of that instead.