|
Boost Users : |
Subject: Re: [Boost-users] Aliased parameters in boost::bind
From: Evgeny Fraimovitch (evgeny_at_[hidden])
Date: 2017-03-29 22:59:33
>> For instance, given the function:
>> void f(std::string x, std::string y, std::string z) {
>> std::cout << x << y << z;
>> }
>> One could following the tutorial naively write:
>> auto triple = boost::bind(f, _1, _1, _1);
>>
>> and this would even work for:
>> std::string x = "a pretty long string"; triple(x); printing the string
>> thrice, as expected.
>> However the result of triple(std::string("a pretty long string"))
>> would be the string only printed once, which is hardly what the user
would expect.
>> In fact, any bind expression produced with aliasing would be sensitive
>> to the type of the reference passed, violating the functor abstraction
badly.
> Why would you declare f as copying its parameters by value instead of
taking them by const& instead? const& parameters would be safe in this
case.
> const& parameters should be your default for anything with non-trivial
copy/move behaviour anyway, so you'd only run into this issue in already-bad
code.
> Although it would be nice if there were some way to emit a compiler
warning for this sort of construct, I agree.
Although the code is suboptimal, I do not agree it is bad. This lack of pass
by reference in this case should not be affecting correctness, since we are
not going to modify the object. Also, it might not be std::string. Shared
points are often passed by value and they exhibit the same issue. They can
be passed as const reference too, as an optimization, however whether this
justifies additional clutter in the parameter list is a matter of personal
taste.
I can think of no other situation where there would be a semantic difference
in passing by (const) value vs passing by const reference.
Sincerely yours,
Evgeny
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