Memory leak when using std::function with std::bind in C++20
I'm trying to configure I'm stuck on something that should probably be simple. I'm working on a personal project and I'm experiencing a memory leak in my C++20 application when using `std::function` with `std::bind`. I have a class that sets up a callback mechanism for event handling, and I bind member functions to the callbacks. However, I'm noticing that the memory usage increases steadily over time, even though the callbacks should be released after their use. Hereβs a simplified version of my code: ```cpp #include <iostream> #include <functional> #include <vector> #include <memory> class EventHandler { public: void registerCallback(std::function<void()> callback) { callbacks.push_back(callback); } void triggerEvents() { for (const auto& callback : callbacks) { callback(); } } private: std::vector<std::function<void()>> callbacks; }; class MyClass { public: void handleEvent() { std::cout << "Event handled!" << std::endl; } }; int main() { EventHandler handler; MyClass obj; handler.registerCallback(std::bind(&MyClass::handleEvent, &obj)); handler.triggerEvents(); // Simulating multiple calls for (int i = 0; i < 10000; ++i) { handler.triggerEvents(); } return 0; } ``` When I run this code, I notice that memory consumption keeps growing in my application, suggesting that something is not being cleaned up correctly. I've verified that I'm not holding onto references longer than necessary, and the callbacks should be invoked and cleaned up after each call to `triggerEvents()`. Also, I tried using `std::weak_ptr` instead of raw pointers in my bind call to see if it made a difference, but the memory leak still continues. I suspect that there is a question with how `std::function` is handling these bound member function callbacks, possibly related to how the object's lifetime is managed. Is there a known scenario with this pattern in C++20, or is there a more effective way to manage callback lifetimes without incurring memory leaks? What's the best practice here? My development environment is Ubuntu. This is part of a larger service I'm building. I'd really appreciate any guidance on this.