lundi 19 avril 2021

Error adding slots using lambdas (Boost Signals2)

The code below prints worldworld to the console rather than hello world. I can fix this by changing sig.connect([&]() { slot(); }); to sig.connect(slot), but don't understand why. What's happening?

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

void add_slot(boost::signals2::signal<void()> &sig,
              std::function<void()> slot) {
  sig.connect([&]() { slot(); });
}

int main() {
  boost::signals2::signal<void()> sig;
  add_slot(sig, []() {
    std::cout << "hello ";
  });
  add_slot(sig, []() {
    std::cout << "world";
  });
  sig();
}

Aucun commentaire:

Enregistrer un commentaire