gpt4 book ai didi

c++ - 如何使用仿函数从 boost 信号 2 断开连接到类的方法?

转载 作者:搜寻专家 更新时间:2023-10-31 00:54:06 25 4
gpt4 key购买 nike

从 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

最佳答案

使用 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.

关于c++ - 如何使用仿函数从 boost 信号 2 断开连接到类的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46371238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com