What exactly happens if I delete the object that contains this lambda inside the lambda?

I have a callback system in which lambdas is emitted when something happens. To receive a notification, you need to register the lambda in the identifier or cancel the registration if you do not want to be notified again.

The problem that I have is that I have registered lambdas, which on call will unregister from this system, which will lead to the destruction of the current lambdas. And I think this is unsafe. But I'm not sure.

Simplification, 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;
}

I see that when I check the state of lambda after m.clear(), I get strange behavior (for example, it std::coutdoesn't work). Can you explain to me what exactly happens in these cases?

? (, -)?

+4
1

, : , std::function<void()>.

std::function . std::map.

std::map std::map::clear, std::function.

std::map::clear cppreference.org:

. , , . .

, clear ing std::map , . , , undefined .


, :

using func = std::function<void()>;

func f;
f = [&f]{ int a = 0; f.~func(); std::cout << a; };
+5

Source: https://habr.com/ru/post/1671988/


All Articles