Skip to content

Commit

Permalink
fix: Safely capture this as weak_ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
mrousavy committed Feb 24, 2024
1 parent d7a2afb commit a34f852
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions package/cpp/ListenerManager.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,31 @@
#include <algorithm>
#include <functional>
#include <list>
#include <memory>

namespace margelo {

template <typename Callback> class ListenerManager {
template <typename Callback> class ListenerManager : public std::enable_shared_from_this<ListenerManager<Callback>> {
private:
using TSelf = ListenerManager<Callback>;
std::list<Callback> _listeners;

private:
std::shared_ptr<ListenerManager<Callback>> shared() {
return this->shared_from_this();
}

public:
Listener add(Callback listener) {
_listeners.push_back(std::move(listener));
auto id = --_listeners.end();
return Listener([id, this]() { _listeners.erase(id); });
auto weakThis = std::weak_ptr<TSelf>(shared());
return Listener([id, weakThis]() {
auto sharedThis = weakThis.lock();
if (sharedThis) {
sharedThis->_listeners.erase(id);
}
});
}

const std::list<Callback>& getListeners() {
Expand Down

0 comments on commit a34f852

Please sign in to comment.