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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With