Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda captured by reference and used in slot

Tags:

c++

c++14

I have C++14 code similar to this:

void C::f() {
  int& ref = this->x;
  auto lb = [&ref]() {
    /* do stuff with "ref" */
  };
  if (foobar) {
    // call lb when signal fires. 
    connect(object, &D::signal, [&lb]() {
      lb();
    });
  } else {
    lb();
  }
}

I know that by the time I use lb, this will still be valid. But what about ref and lb. Is there any dangling reference with the code above ?

I found similar questions (here, there,...) but I couldn't draw a conclusion.

like image 357
Davidbrcz Avatar asked May 16 '19 09:05

Davidbrcz


1 Answers

lb has automatic storage, so references to it become invalid when this function returns.

The validity of ref depends on the lifetime of *this.
(The lambda isn't capturing the variable ref by reference, it's capturing a reference to the object that ref refers to.)

like image 127
molbdnilo Avatar answered Nov 15 '22 12:11

molbdnilo