0
class A{
public:
    void do_something(std::function<void()> const& f) {

    }
};

class B: public A{
public:
    int x = 0;
    void do_another_thing(){
     do_something([x]{});   
    }
};

It says that x is not a variable:

16:20: error: capture of non-variable 'B::x' 
14:13: note: 'int B::x' declared here

Why it won't work with a class member but it will work with variables defined inside do_another_thing()?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 1
    [Why can't a data member be in a lambda capture list](https://stackoverflow.com/questions/23803152/why-cant-a-data-member-be-in-a-lambda-capture-list), [Lambda captures and member variables](https://stackoverflow.com/questions/17197997/lambda-captures-and-member-variables) – t.niese Sep 13 '19 at 04:28
  • Adding to above links, here is iso std reference:- §5.1.2 Lambda expressions #13 "... If a lambda-expression captures an entity and that entity is not defined or captured in the immediately enclosing lambda expression or function, the program is ill-formed. ..." – The Philomath Sep 13 '19 at 04:35

1 Answers1

1

void do_another_thing() {
do_something([x]{});
}

The problem is that x is not a variable within the immediate scope of the lambda definition. Hence it cannot be captured. Agreed that x is a class member declared just above the function, but that doesn't make it visible to the lambda. You could capture this instead.

jignatius
  • 6,304
  • 2
  • 15
  • 30