vendredi 10 mars 2017

What exactly happens if I delete inside a lambda the object that holds that lambda?

I have a callback system that holds lambdas to be emitted when something happens. To get notified you have to register the lambda to an identifier, or unregister if you don't want to be notified again.

The problem that I have is that I have lambdas registered that on called will unregister from that system causing the destruction of the current lambda being executed. And I think this is not safe. But I'm not sure.

Simplifying for example:

#include <map>
#include <functional>
#include <iostream>


int main() {
  std::map<int, std::function<void ()>> m;
  m[10] = [&m] () {
    int i = m.size();  // Just cheking the internal state of the lambda
    m.clear();
    //i += m.size();   // If I uncomment this the std::cout is not working.
    std::cout<< "What happens? " << i << std::endl;
  };

  m[10]();

  return 0;
}

What I'm seeing is that when I check the state of the lambda after m.clear(), I get strange behaviour (for example std::cout not working). Can you explain me what happens exactly in those cases?

How will you handle those situations with callbacks? making a copy before calling the callback (seems a no-no)?

Aucun commentaire:

Enregistrer un commentaire