Boost logo

Boost :

From: Jaakko Jarvi (jajarvi_at_[hidden])
Date: 2004-04-15 11:28:52


On Apr 15, 2004, at 11:08 AM, Dill, John wrote:

>>> While having pass-by-value
>>> may be more convenient and occur more often, the
>>> counter-intuitiveness
>>> of the semantics will lead to subtle bugs in people's code who
>>> misunderstand or forget bind's behavior in this area.
>>
>> A bold prediction in the face of contradictory evidence.
>
> Can you elaborate? You may have no problems understanding the
> library, but the first time I tried to bind with a reference, I ran
> into the same confusion. I am speaking from my own limited experience
> with the library. I've read the documentation:
>
> // Start of docs
> The arguments that bind takes are copied and held internally by the
> returned function object. For example, in the following code:
>
> int i = 5;
>
> bind(f, i, _1);
>
> a copy of the value of i is stored into the function object.
> boost::ref and boost::cref can be used to make the function object
> store a reference to an object, rather than a copy:
>
> int i = 5;
>
> bind(f, ref(i), _1);
> // End of docs
>
> I know this makes it explicit that you need a ref or cref to have bind
> store a reference to an object, but there is no reasoning behind this
> design decision in the documentation, or that I can find in the
> implementation and I've not stumbled across it in the mail archives.
>

Hello John,

There's a big technical reason:

If bind would have reference semantics, you could not do this:

bind(f, 1, _1)

Bind would have to take its arguments as

template <class F, class A, class B, ...>
bind( F, A&, B&, ...)

1 is a non-const rvalue, which cannot be bound to non-const reference.

Cheers,

   Jaakko


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk