Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2004-02-19 14:07:52


Brian McNamara wrote:
> On Thu, Feb 19, 2004 at 03:46:01PM +0200, Peter Dimov wrote:
>
>> But I'm not sure that this is true. It seems to me that the rule is
>> that I should use ref(x) if my x will outlive the function object,
>> as in the above, and a plain x otherwise, and it will "just work".
>
> This is not the rule I desire (though it is one possible way to go).
> I don't like this rule because it is deciding "whether to reference or
> not" based on the argument, rather than on the function. That is, in
> the case of
>
> app(_, x)(f);
>
> I don't want to pass "x" by reference simply because it appears be be
> a non-transient object with sufficient lifetime. "f" doesn't need a
> reference, so I shouldn't be creating one.

The rule as I stated it is for the programmer, not for the library. The rule
that bind() uses (or, more precisely, approximates) is: all arguments to
bind() are copied. The function object created by bind() does no copies and
just forwards.

Now obviously given the forwarding problem this is not possible to implement
in the general case, but that's the intent.

> In any case, the question of "if my x will outlive the function
> object" is non-trivial. Consider
>
> // assume h is a functoid with signature int h(int&,int)
> // assume l is a list<int>
> {
> int x = 1;
> l = map( h(x), l ); // note that "h(x)" means "h(x,_)"
> }
>
> Does "x" outlive the function object? Is it reasonable to pass "x" by
> reference?
>
> The answer to both is no. Functional programming idioms often create
> less-than-obvious lifetime issues. In the case above, the function
> object outlives "x", because "l" is a lazy list and it stores the
> function object so that list elements can later be computed on-demand.

Right, that is why bind() makes a copy by default, unless a reference is
explicitly specified with ref().

> Right, sorry; I was unclear. The function objects created via lambda
> expressions always take non-const reference parameters. In contrast,
> FC++ function objects always take const reference parameters.
> (And, in both libraries, partial application makes a copy of the bound
> arguments.)
>
> (Is this right?)

Yes, this is correct, except that the function objects take a templated
reference to whatever constness the actual argument has.

I'm not saying that your approach is incorrect, I just wanted to understand
the differences in implementation and philosophy.


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