如何使用函子从升压信号 2 断开连接到 class 的方法?

How do you disconnect from a boost signal2 using a functor to a method of a class?

从 boost::signals2 断开插槽(即 class 方法)时,我没有得到预期的行为。我的术语可能不适用,所以我将在下面提供一个最小工作示例 (MWE),以展示我所看到的和我期望的。简短的版本是我正在断开信号,但它留在那里。如果我使用独立函数执行此操作,一切都会很好,当我使用 class 方法时,我 运行 进入此行为。

如有任何帮助,我们将不胜感激!

>> 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

我使用连接方法返回的 boost::signals2::connection 对象与 boost::signal2::signal 断开连接。

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