c++qtboostqtcoreqt-signals

what's the utility of signals and slots


Actually I have been using signals and slots while programing in Qt. The main use of signals and slots are in the UI interaction, for example a clicked button sends a signal that will invoke a slot to perform action. I know that it's possible to use signals and slots for non-gui application, for example a server side application. I looked for other libraries that offers signal and slots and I found boost library. It's some how different from what I learned from Qt. And then I was wondering what's the real utility of signals and slots, since I can manually call a function to perform an action at a given time.

for example in boost here is an example of signals/slots :

#include <boost/signals2.hpp>
#include <iostream>

void mySlot(){
  std::cout << "I'm a slot" << std::endl;
}

void main(){
  boost::signals2::signal<void ()> sig;
  // Connecting the slot to the signal.
  sig.connect(mySlot);

  // Emitting a signal that will call mySlot 
  sig();

  return 0;
}

I could simply do the same thing with a simple call of mySlot() isn't it ?

Not that what made me think is that when we try to connect two different slots, they are called in the same order than connection. and if the first slot is blocking ( try to add an infinite loop) the second slots will never be called ! I guess that it's a kind of vector that stores the addresses of the functions and then iterate the loop and call one by one !

What's the magic behind the signals and slots ? or it's only a kind of abstraction for the developer ?

Thank you in advance.


Solution

  • In short: The main idea is decoupling in my opinion.

    In longer: With direct function calls, you could not have a well-separate establishment between the common functionality and the clients of it, for instance. There would be a tight coupling unlike with signals and slots because you would need to know at the point of some condition meeting your criteria which methods exactly to call.

    If you would like to gain more freedom, like with many other OOP design patterns, you need something like signals and slots. When a common component, let us call it a library, emits a signal, it does not have to be aware of the (potentially not-yet-existing) client interfaces. This makes the common component flexible enough.

    It will also keep responsiveness of the application better since it is not a direct call, but processed by the Qt event loop. Arguably, you could circumvent this with custom threading mechanisms, but that would be lotta more work to make it safe enough, and you would end up doing something close this in the end of the day.