使用重新实现
scoped_connection
:
#include <boost/signals2.hpp>
#include <iostream>
struct foo {
void bar(int n) {
std::cout << "Called foo::bar with " << n << std::endl;
}
};
typedef boost::function<void(int)> Signal_f;
int main() {
using boost::signals2::scoped_connection;
foo f;
boost::signals2::signal< void(int) > my_signal;
Signal_f functor = boost::bind(&foo::bar, f, _1);
std::cout << "Created signal, and it has "
<< my_signal.num_slots() << " subscribers." << std::endl;
// the scoped_connection object is RAII
auto con = scoped_connection(my_signal.connect(functor));
std::cout << "Subscribed to signal, and it has "
<< my_signal.num_slots() << " subsciber." << std::endl;
my_signal(1);
// disconnect the connection object, not the signal
con.disconnect();
std::cout << "Un-Subscribed to signal, and it now has "
<< my_signal.num_slots()
<< " subscibers." << std::endl;
my_signal(2);
return 0;
}
Created signal, and it has 0 subscribers.
Subscribed to signal, and it has 1 subsciber.
Called foo::bar with 1
Un-Subscribed to signal, and it still has 0 subscibers.