Search code examples
c++boostboost-signals2

Connect pointer to boost::signals2


I was wondering if somehow it was possible to connect a pointer to a boost::signals2::signal. For my problem is the following : I want the object connected to the "signal" to be changed. For instance :

class Something
{
    public:
        int x;
        bool operator()(std::string str)
        {
            std::cout << str << x << std::endl;
            return true;
        }
};


int main()
{
    boost::signals2::signal<bool (std::string)> sig;
    Something something;
    something.x = 3;
    Something* somethingElse = new Something;
    somethingElse->x = 3;
    sig.connect(something);
    sig.connect(*somethingElse); 

    something.x = 2;
    somethingElse->x = 2;

    sig("x is : ");
}

The code will always output :

x is : 3

and I would like it to output

x is : 2

Now I feel like I am missing something, either an easy solution, or a good understanding of what the boost::signals2 are for.


Solution

  • You just need to ref-wrap the functor you want to pass by reference (note that you will have to ensure the signal is disconnected before the functor goes out of scope).

    Something something;
    something.x = 3;
    
    Something somethingElse;
    somethingElse.x = 3;
    
    sig.connect(something);
    sig.connect(boost::ref(somethingElse)); 
    
    something.x = 2;
    somethingElse.x = 2;
    
    sig("x is : ");
    

    This will print

    x is : 3
    x is : 2
    

    See it Live On Coliru