Skip to content

Instantly share code, notes, and snippets.

@nboutin
Created February 18, 2023 20:27
Show Gist options
  • Select an option

  • Save nboutin/7775e59e8f774336bf8aca5c3e545743 to your computer and use it in GitHub Desktop.

Select an option

Save nboutin/7775e59e8f774336bf8aca5c3e545743 to your computer and use it in GitHub Desktop.

Revisions

  1. nboutin created this gist Feb 18, 2023.
    23 changes: 23 additions & 0 deletions raii_subscribe_unsubscribe.cpp
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    // https://www.youtube.com/watch?v=nLSm3Haxz0I

    class EventSource
    {
    void add(Listener& listener);
    void remove(Listener& listener);
    public:
    [[nodiscard]]
    Subscription subscribe(Listener& listener) {
    return Subscription(*this, listener); }
    };

    class EventSource::Subscription
    {
    Subscription(EventSource& source, Listener& listener)
    : source_(source), listener_(listener)
    { source_.add_listener(listener_); }

    ~Subscription()
    { source_.remove(listener_);}

    // special function members
    };