Is it allowed to delete a lambda object while executing the associated lambda function, as long as precautions are taken not to access any of the captured state after the deletion?
Consider the following example:
int main() {
int x = 1;
std::function<void()> d;
auto l = new auto([x, &d]() {
fmt::print("x is {}\n", x);
d();
fmt::print("I'm deleted\n");
});
d = [l](){ delete l; };
(*l)();
}
Here, the lambda pointed to by l deletes itself using a Rube Goldberg-like approach through the d function1. After the deletion it prints a fixed message which doesn't access any captured state.
Is it defined behavior?
1 I couldn't figure out a better way to break the circular dependency between the lambda code which needs to see something that points to itself: I'm open to better options.