0

In a signal/slot system you connect a slot to a signal. The slot can be anything, a lambda object, that may go out of scope, an instance pointer/member function pointer pair, a function pointer. The latter slots cannot be invalidated.

My question is how to deal with slots that may get invalidated, such as instance pointer/member pointer pairs and lambda objects. One could copy lambda objects, but they may still have captured something that got invalidated (such as an instance pointer).

user1095108
  • 14,119
  • 9
  • 58
  • 116

1 Answers1

0

Be creative: you might exploit the mutable keyword for a lambda function to be notified in advance whether a captured value is no longer valid (and be able to change read-only captured variables)

#include <iostream>
using namespace std;

int main() {

    int *num = new int(0x90);

    auto lambda = [=] (bool ptrHasChanged = false) mutable { if(ptrHasChanged) num = new int(0x1); cout << *num << endl; if(ptrHasChanged) delete num;};

    lambda();

    delete num;

    lambda(true);

    return 0;
}

if you're capturing class objects and using their member variables (always by reference since you capture the this pointer by value) it is your responsibility to deal with the scopes.

Simpler solution is to regenerate the lambda each time you need it, although I'm not sure what the cost would be.

Marco A.
  • 43,032
  • 26
  • 132
  • 246