Boost logo

Boost Users :

Subject: Re: [Boost-users] Beginner question: Why boost::signal creates another instance of the slot object ?
From: Lars Viklund (zao_at_[hidden])
Date: 2010-08-20 03:52:18


On Thu, Aug 19, 2010 at 05:29:20PM -0700, Steven Watanabe wrote:
> Mauricio Gomes wrote:
>> Just for my education, what is the rationale behind making a copy of
>> the signaled object ?
>> It seems odd to me since the object interested in receiving the event
>> ends up not receiving it (unless we use boost::ref).
> Passing function objects by value is the normal
> convention in C++. There are many cases where
> it is the correct behavior. For example, if you
> you connect a function object created by boost::bind
> to the signal, the function object is a temporary and
> is destroyed immediately. If it were stored by
> reference, the boost::signal would be left with
> an invalid reference. Don't think of the function
> object as the object receiving the signal. The
> function object is an action to be performed.
>> I am obviously missing something conceptually here. If you or anyone
>> could explain it to me I'd really appreciate.

As Steven outlines, if you have a callable in C++, you should expect it
to be copied, a lot.

As such, you should make it lightweight and cheap to copy, preferably
holding any shared state with shared_ptrs or weak_ptrs, or if lifetimes
are known to exceed the lifetime of the callable, by reference or

It's awfully hard to hold on to something by reference for a longer
period, as that unnecessarily puts the onus on the caller to ensure that
an unknown lifetime is guaranteed.

As for your initial problem of the receiver being dis-associated from
the callable, it's probably because it's not properly copyable.

It's normally good form to make things that should not be copied
boost::noncopyable or otherwise artificially restricted from copying, in
order to catch such assumptions at an early stage instead of through
runtime bugs.

Lars Viklund | zao_at_[hidden]

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at