'this' used in initializer list - Dangerous?

closed account (3hM2Nwbp)
I'm wary of this code because of the warning that's being thrown, but I can't for the life of me see how it could be dangerous in this case unless the lambda expression does something funky with 'this'. Am I being paranoid or am I missing something? GCC didn't generate a warning for it on my linux box, but MSVC did. How exactly is 'this' captured in the lambda expression? Is the behavior implementation defined regarding how 'this' is used in the expression?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct Timer
{
    Timer(unsigned int, std::function<bool(void)>);
    void tick();
};

class Test
{

  public:

    Test(void)
      : someTimer(300, [&](void)->bool{someVariable = 4; return false;})
    {

    }

  private:

    Timer someTimer;

    int someVariable;

};
Last edited on
How exactly is 'this' captured in the lambda expression?

like this:

[&](void)->bool{this->someVariable = 4; return false;}

Is the behavior implementation defined regarding how 'this' is used in the expression?

You'll be in undefined behaviour territory if Timer's constructor calls that lambda. If you ensure that your Test object gets fully constructed before the Timer calls that function then you should be fine.
Topic archived. No new replies allowed.