Boost logo

Boost Users :

Subject: Re: [Boost-users] shared_ptr and signals
From: Max (loadcom_at_[hidden])
Date: 2009-01-01 23:08:57


Hello,

Perhaps nobody is aware of (perpahs some are) that this simple
use case has introduced another intersting and, probably, very
useful scenario in which the Signals lib could be benificial.

That is:

Slot With Status.

Have a look at this example:

struct Slot
{
        int sum;
        Slot() : sum(0) {}
        Slot(int i) : sum(i) {}
        int operator()(int i) { return sum += i; }
};

void test_signals()
{
        typedef boost::signal<int(int)> Signal;
        Signal sig;

        boost::shared_ptr<Slot> a( new Slot() );
        boost::shared_ptr<Slot> b = a;
        sig.connect(boost::bind( &Slot::operator(), a, _1));
        sig.connect(boost::bind( &Slot::operator(), b, _1));
        sig.connect(boost::bind( &Slot::operator(), boost::shared_ptr<Slot>(a), _1));
        std::cout << "\na.use_count() = " << a.use_count();

        std::cout << "\nsum = " << sig(1) << std::endl;
}

The result is:

a.use_count() = 5
sum = 3

the reason of use_count of the shared_ptr being 5 rather than 3 is
the result of the copy semantics of the connect function.

Hope this information is interesting.

B/Rgds
Max



----- Original Message -----
From: Frank Mori Hess <fmhess_at_[hidden]>
To: boost-users_at_[hidden]
Subject: Re: [Boost-users] shared_ptr and signals
Date: 2009-1-1 01:30:05

On Tue Dec 30 12:47 , Steven Watanabe <watanabesj_at_[hidden]> sent:

>James C. Sutherland wrote:
>> Is it possible to use a shared_ptr object in a signal?
>>
>> I want something like
>>
>> struct A{
>> ...
>> void operator()(){ ... }
>> ...
>> };
>> typedef boost::signal Signal;
>> Signal mySignal;
>>
>> boost::shared_ptr a( new A() );
>> mySignal.connect(a);

>Wrap the shared_ptr in a function object
>
>struct deref_call {
> void operator()() const {
> (*f)();
> }
> boost::shared_ptr f;
>};

bind can also be used to do this, since shared_ptr can be passed as the
"this" argument when binding member functions:

boost::shared_ptr a( new A() );
mySignal.connect(boost::bind(&A::operator(), a));

-------------------------------------------------------------------
ÐÂÀ˿ռ䡪¡ªÓëÅóÓÑ¿ªÐÄ·ÖÏíÍøÂçÐÂÉú»î£¡(http://space.sina.com.cn/ )


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net