Segmentation fault when using std::function with lambda capturing local variables in C++20
I've been working on this all day and I'm working with a segmentation fault in my C++20 application when trying to use `std::function` with a lambda that captures local variables. I have a class that manages a resource, and I want to schedule a cleanup function that relies on state stored in this class. Here's a simplified version of my code: ```cpp #include <iostream> #include <functional> #include <memory> #include <thread> class ResourceManager { public: ResourceManager(int id) : resource_id(id) {} ~ResourceManager() { std::cout << "Resource " << resource_id << " cleaned up!\n"; } void scheduleCleanup() { auto cleanup = [this]() { delete this; // Attempt to delete the instance }; std::function<void()> func = cleanup; std::thread([func]() { func(); }).detach(); } private: int resource_id; }; int main() { ResourceManager* manager = new ResourceManager(1); manager->scheduleCleanup(); std::this_thread::sleep_for(std::chrono::seconds(1)); // Wait for cleanup return 0; } ``` When I run this code, I get a segmentation fault at runtime. I believe the scenario lies in how the lambda captures `this` and the timing of the object's destruction. I tried changing the lambda to use a `std::shared_ptr` to manage the resource but that didn't resolve the scenario either. Could someone guide to understand why this is happening and how I can safely schedule the cleanup without causing a segmentation fault? Is this even possible? I'm using C++ 3.10 in this project. Thanks for taking the time to read this!