2014-09-25 15 views
1

我期望以下完整程序輸出數字42,但它輸出0。爲什麼?由升壓信號2信號調用的函數的成員變量不更新

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

class TestFunctor { 
public: 
    TestFunctor() : last_received_value(0) {} 
    void operator()(const int& i) { 
     last_received_value = i; 
    }; 

    int last_received_value; 
}; 

int main(int argc, char* argv[]) { 
    TestFunctor f; 
    boost::signals2::signal<void(const int& i)> sig; 
    sig.connect(f); 
    sig(42); 
    std::cout << f.last_received_value << std::endl; 
    return 0; 
} 

如果main()用下述內容代替,我得到的預期輸出42

int main(int argc, char* argv[]) { 
    TestFunctor f; 
    f(42); 
    std::cout << f.last_received_value << std::endl; 
    return 0; 
} 

我懷疑的問題是,TestFunctor實例的副本實際上是被掛接到信號。我怎樣才能防止這個(或甚至可能)?

回答

2

您需要通過裁判註冊回調:

sig.connect(boost::ref(f)); 

否則,插槽得到函子f的副本和副本更新。

+0

完美。謝謝。 – Steve 2014-09-25 21:44:56