How and why one would use Boost signals2?

前端 未结 1 438
死守一世寂寞
死守一世寂寞 2020-12-13 07:36

Learning c++ and trying to get familiar with some patterns. The signals2 doc clearly has a vast array of things I can do with slots and signals. What I don\'t understand is

相关标签:
1条回答
  • 2020-12-13 07:55

    Boost.Signals2 is not just "an array of callbacks", it has a lot of added value. IMO, the most important points are:

    1. Thread-safety: several threads may connect/disconnect/invoke the same signal concurrently, without introducing race conditions. This is especially useful when communicating with an asynchronous subsystem, like an Active Object running in its own thread.
    2. connection and scoped_connection handles that allow disconnection without having direct access to the signal. Note that this is the only way to disconnect incomparable slots, like boost::function (or std::function).
    3. Temporary slot blocking. Provides a clean way to temporarily disable a listening module (eg. when a user requests to pause receiving messages in a view).
    4. Automatic slot lifespan tracking: a signal disconnects automatically from "expired" slots. Consider the situation when a slot is a binder referencing a non-copyable object managed by shared_ptrs:

      shared_ptr<listener> l = listener::create();
      auto slot = bind(&listener::listen, l.get()); // we don't want aSignal_ to affect `listener` lifespan
      aSignal_.connect(your_signal_type::slot_type(slot).track(l)); // but do want to disconnect automatically when it gets destroyed
      

    Certainly, one can re-implement all the above functionality on his own "using a vector of functions and calling each one in a loop" etc, but the question is how it would be better than Boost.Signals2. Re-inventing the wheel is rarely a good idea.

    0 讨论(0)
提交回复
热议问题