【发布时间】:2017-09-22 18:38:03
【问题描述】:
从 boost::signals2 断开插槽(即类方法)时,我没有得到预期的行为。我的术语可能是错误的,所以我将在下面提供一个最小的工作示例(MWE)来展示我所看到的和我所期望的。简短的版本是我与信号断开连接,但它一直呆在那里。如果我使用独立函数执行此操作,一切都会很好,当我使用类方法时,我会遇到这种行为。
任何帮助将不胜感激!
>> tree
.
├── main.cpp
└── SConstruct
0 directories, 2 files
>> cat SConstruct
Program('main.cpp')
>> cat main.cpp
#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() {
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;
my_signal.connect(functor);
std::cout << "Subscribed to signal, and it has "
<< my_signal.num_slots() << " subsciber." << std::endl;
my_signal(1);
my_signal.disconnect(&functor);
std::cout << "Un-Subscribed to signal, but it still has "
<< my_signal.num_slots()
<< " subsciber, and it should not have any now." << std::endl;
my_signal(2);
return 0;
}
>> scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o main.o -c main.cpp
g++ -o main main.o
scons: done building targets.
>> ./main
Created signal, and it has 0 subscribers.
Subscribed to signal, and it has 1 subsciber.
Called foo::bar with 1
Un-Subscribed to signal, but it still has 1 subsciber, and it should not have any now.
Called foo::bar with 2
【问题讨论】:
标签: c++ boost publish-subscribe